From 51e14ead6aadd5381db3b923d3c0dd1ad35bc021 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:13:31 +1300 Subject: [PATCH 01/66] feat: converge public Account facade and persisted actor discovery --- .../account-service/api-contracts.md | 20 +- .../account-service/runtime-and-data.md | 2 +- .../api-contracts.md | 8 + .../runtime-and-data.md | 6 + design/project-management/ai-observations.md | 1 + .../gameplay-rules-entities-and-effects.md | 6 + .../player-access-and-session.md | 10 +- protos/account/v1/account_service.proto | 3 + .../player_admission_entitlement_read.proto | 35 + .../v1/account_bootstrap_roster_read.proto | 40 + services/account-service/build.gradle.kts | 5 + .../AccountBootstrapRosterReadClient.java | 198 ++ .../accountservice/dto/BootstrapRealmDto.java | 20 +- .../dto/CanonicalJoinScopeV2.java | 5 + .../dto/DirectTextCallerContext.java | 8 +- .../dto/DirectTextJoinTarget.java | 6 +- .../dto/JoinPublicProductionResult.java | 10 +- .../AccountJoinOperationRepository.java | 311 ++- ...ountMembershipPairAuthorityRepository.java | 89 + .../AccountTenantMembershipRepository.java | 45 + ...ayerAdmissionEntitlementWorkloadGuard.java | 76 + .../AccountCanonicalConnectScopeReader.java | 269 ++ ...CanonicalFirstJoinTerminalCoordinator.java | 279 +- ...AccountCanonicalPublicRealmScopeOwner.java | 191 +- ...countMembershipAuthorityEventProducer.java | 298 ++- ...ccountPlayerAdmissionEntitlementOwner.java | 623 +++++ .../service/impl/AccountGrpcService.java | 78 +- ...PlayerAdmissionEntitlementGrpcService.java | 120 + .../service/impl/AccountServiceImpl.java | 724 ++++- ...l_join_failure_and_attempt_diagnostics.sql | 440 +++ ...ical_join_existing_membership_terminal.sql | 456 ++++ .../src/main/resources/openapi.yaml | 25 +- .../AccountApplicationIntegrationTest.java | 1927 +++++++++++++- ...rUuidEntityCompositionIntegrationTest.java | 1062 +++++--- ...alJoinScopePersistenceIntegrationTest.java | 438 +++ ...anonicalFirstJoinEventIntegrationTest.java | 922 ++++++- ...nicalFirstJoinPostgresIntegrationTest.java | 389 +++ ...titlementOwnerPostgresIntegrationTest.java | 584 ++++ ...emoWorldsOwnerPostgresIntegrationTest.java | 161 +- ...ountBootstrapRosterReadClientMtlsTest.java | 316 +++ .../controller/AuthControllerTest.java | 74 +- .../dto/CanonicalJoinScopeV2Test.java | 9 + ...tJoinOperationRepositoryCanonicalTest.java | 178 +- ...MembershipPairAuthorityRepositoryTest.java | 42 + ...AdmissionEntitlementWorkloadGuardTest.java | 117 + ...ccountCanonicalConnectScopeReaderTest.java | 490 ++++ ...nicalFirstJoinTerminalCoordinatorTest.java | 49 +- ...untCanonicalPublicRealmScopeOwnerTest.java | 171 +- ...thorityEventProducerCanonicalJoinTest.java | 132 +- ...ntPlayerAdmissionEntitlementOwnerTest.java | 941 +++++++ .../service/impl/AccountGrpcServiceTest.java | 99 +- ...erAdmissionEntitlementGrpcServiceTest.java | 47 + .../service/impl/AccountServiceImplTest.java | 2358 ++++++++++++++++- ...imePlayerAdmissionEntitlementEvidence.java | 588 ++++ ...layerAdmissionEntitlementEvidenceTest.java | 298 +++ ...mePlayerAdmissionEntitlementGrpcCodec.java | 161 ++ ...ayerAdmissionEntitlementGrpcCodecTest.java | 279 ++ ...untRuntimeStubServerCompatibilityTest.java | 44 + .../test/AccountRuntimeStubServer.java | 20 +- ...AccountBootstrapRosterActorProjection.java | 13 + ...AccountBootstrapRosterPeerInterceptor.java | 71 + .../AccountBootstrapRosterReadContract.java | 79 + ...AccountBootstrapRosterReadGrpcService.java | 76 + .../AccountBootstrapRosterReadService.java | 95 + .../repository/CharacterRepository.java | 89 +- ...calGameplayRosterOwnerEvidenceAdapter.java | 23 +- ...trapRosterPostgresMtlsIntegrationTest.java | 488 ++++ ...untBootstrapRosterPeerInterceptorTest.java | 108 + ...AccountBootstrapRosterReadServiceTest.java | 219 ++ .../AccountBootstrapRosterFixture.java | 263 ++ .../gamesession/client/AccountClient.java | 4 +- ...countPlayerAdmissionEntitlementClient.java | 338 +++ .../DirectTextAuthenticatedLobbyJoin.java | 1 + ...TextAuthenticatedLobbyIntegrationTest.java | 30 + .../gamesession/client/AccountClientTest.java | 16 + ...yerAdmissionEntitlementClientMtlsTest.java | 432 +++ .../DirectTextAuthenticatedLobbyTest.java | 30 + 77 files changed, 17872 insertions(+), 806 deletions(-) create mode 100644 protos/account/v1/player_admission_entitlement_read.proto create mode 100644 protos/entity-management/v1/account_bootstrap_roster_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1035__canonical_join_failure_and_attempt_diagnostics.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1037__canonical_join_existing_membership_terminal.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java create mode 100644 services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3627a6d2eb..bc46f06572 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -125,7 +125,9 @@ Fresh-enrollment certification is internal Account owner work, not a public regi The UUID billing foundation archives numeric subscription rows as immutable, non-authorizing retained evidence and supplies canonical intent, provisioning, lifecycle and cancellation-recovery storage. It also prepares the distinct `TENANT_OPERATION` source and protected transport; these owners remain manually composed and unregistered. Detailed receiving proof and unfinished authority boundaries belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). -The existing public WORLDS, REALMS, CHARS, browser/direct JOIN, direct scope and connect-token facades currently return `AUTH_UNAVAILABLE` before legacy discovery or subscription reads. The complete canonical UUID public facade and positive compositions remain in the preserved receiving successor. Ordinary authentication/player-bootstrap identity remains available. Retained numeric rows never authorize current billing or admission. +The public WORLDS/REALMS, browser/direct JOIN and CHARS facades now delegate to explicitly composed canonical UUID owners and the retained V2 reader; absent composition returns `AUTH_UNAVAILABLE` before legacy sources. JOIN captures actual Account intent/member/pair/role/event/audit state, reads protected Game Session/World and provider sources outside SQL, then revalidates in its final Account transaction. Existing ACTIVE membership returns its truthful snapshot without repair; INACTIVE restoration advances its membership version/event. `gameplayAdmissionAllowed` is an explicit result and a successful membership response cannot grant gameplay when false. + +CHARS requires the verified browser bootstrap caller and exact retained target, fresh membership and entitlement before the purpose-specific [Entity persisted discovery read](../entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery), followed by fresh caller/member/entitlement/target checks. Only supported SHARED/PRESEEDED_ONLY targets may return actual persisted actors or a valid empty result. Unsupported private/isolated/player-created/auto-provisioned discovery is unavailable rather than an empty success. Discovery creates no selection, actor, retention or admission authority. Complete source protection through a later commit, default registration and canonical runtime cutover remain unfinished; [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns proof and remaining scope. The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: authorization and HELD read use `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`; source read uses `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`; settlement uses `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. @@ -193,7 +195,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `CreateAccount` – registers a global Account identity and returns its canonical UUID as REST `AccountDto.id` and gRPC `CreateAccountResponse.account_id`; its platform audit outbox payload carries the same UUID. It does not select a tenant or create membership/profile state. - `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`. 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. -- `JoinPublicProductionMembership` – prepared internal Account interface for explicit public-production membership creation/restoration; the current receiving facade returns `AUTH_UNAVAILABLE` pending its complete canonical consumer. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds the versioned digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. +- `JoinPublicProductionMembership` – prepared internal Account interface for explicit public-production membership creation/restoration; the canonical consumer is explicitly composed and refuses absent source composition before any legacy authority read. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds the versioned digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `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. @@ -454,6 +456,20 @@ The canonical membership, entitlement response shape, freshness, and sequence co - `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. +### Private player-admission entitlement read + +The distinct [PLAYER_ADMISSION protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto) carries the complete retained canonical target selector, Account-issued connect scope and explicit initial Game Session Account-delegation credential. The manually composed Account receiver authenticates the exact same-namespace Game Session workload before decoding, then its existing caller/current-source owners verify the credential and capture current Account membership/entitlement and protected target evidence. Ambient bearer or caller-supplied workload context cannot replace transport identity. The response echoes the closed selectors and carries canonical PLAYER_ADMISSION evidence without echoing the credential; absent/unavailable authority never becomes a successful empty response or demo fallback. + +The [closed wire codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns the executable size/deadline bounds and exact comparison rules. `scopeDigest` preserves the exact retained V2 `sha256:`-prefixed digest; token/registry SHA-256 fields retain their distinct raw-hex representation. This protected read supplies evidence rather than membership repair, actor selection, capacity or gameplay admission. The receiver and Game Session client remain explicitly composed and unregistered; canonical runtime cutover and complete source protection remain unfinished in the [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). + +### Private tenant-operation entitlement read + +The [closed private protobuf](../../../../protos/account/v1/tenant_operation_entitlement_read.proto) defines `AccountTenantOperationEntitlementReadService.ReadTenantOperationEntitlement` for the exact same-namespace World Management workload over mutually authenticated TLS. The receiver derives the peer from transport certificates and rejects bearer, end-user, internal-service context or a caller-supplied workload identity as substitutes. The request carries only canonical target namespace, tenant UUID, request UUID and an explicit `PAID_HOSTING` or `NON_PAID_DEMO` source choice. Each declared transport member occurs exactly once; unknown fields, duplicate members, malformed selectors and wrong namespaces fail closed. Failed or absent paid authority never selects demo authority. + +The response echoes the exact closed request and carries one canonical `TENANT_OPERATION` value defined by [Runtime Entitlement Evidence Variants](./runtime-and-data.md#runtime-entitlement-evidence-variants). The transport codec verifies the exact tenant, request, source choice and TLS-derived expected World workload; it delegates content validation to that canonical owner. The request is bounded to 1 KiB, canonical evidence to 64 KiB and the complete response to 66,592 bytes, with a five-second World client deadline. Source unavailability yields no positive response or fallback. A protected read supplies source evidence rather than a player subject, capacity commitment or admission grant; action owners retain their currentness and commit fences. + +The private receiver and reloading client remain explicitly composed and unregistered. Their source, controlled transport proof and runtime-cutover limits are recorded in the [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#entitlement-read-and-join-failure-classification). + ## Subject-Binding Rules (Normative) - `GET /tenants/{tenantId}/profiles/{accountId}` and `PUT /tenants/{tenantId}/profiles/{accountId}` are tenant-qualified, caller-subject-bound profile routes. They require live membership and the path `accountId` must equal the authenticated account; global roles do not broaden these routes. Cross-account moderation/support views require separate minimized contracts. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 99d5891076..835f7b09d6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -316,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer remains in its receiving successor. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) owns receiving proof and gaps. +The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is being qualified in the canonical public receiving branch. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) owns receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 5dd85c3b74..ec2afba336 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -291,3 +291,11 @@ The current contract still leaves player command orchestration, authored stat/co - **Live:** The seeded `firemud.look.rooms` entries provide the visible entities for the demo rooms, `ListRoomEntities` is wired into Game Logic's `ResolveLook`, and the resulting instrumentation is captured in [`look-instrumentation.md`](../../../project-management/slice-support/look-instrumentation.md). - **Stubbed:** Real-time behaviors such as item respawns, stealth/aura-driven visibility, and inventory states still rely on static fixtures so regression tests remain reproducible. - **Deferred:** Future slices may consume read-only location metadata from the target `character_location` and `npc_location` tables, which are World Management-owned and currently absent; Entity Management is not the location authority and must not create competing tables or fields. Those slices will support multi-instance visibility rules and surface richer context hints (combat alerts, quest markers) while keeping the public DTO focused on display data. + +## Account bootstrap persisted actor discovery + +`AccountBootstrapRosterReadService.ReadAccountBootstrapRoster` in [account_bootstrap_roster_read.proto](../../../../protos/entity-management/v1/account_bootstrap_roster_read.proto) is a distinct manually composed, unregistered, non-admitting Account discovery boundary. Its purpose-specific certificate interceptor authenticates only the exact same-workload-namespace `account-service` mTLS peer before message decoding. Missing identity is `UNAUTHENTICATED`; another workload/namespace, ambient caller/role or internal-service context, and a request namespace differing from the configured workload namespace are `PERMISSION_DENIED`. The existing canonical roster methods remain Game Session-only and unchanged; ordinary `ListCharactersByAccount` is not a substitute. + +The closed request contains canonical non-nil request and Account UUIDs, the configured workload namespace and the complete existing `CanonicalGameplayRosterTarget`, including every source digest, release reference and positive owner counter. It carries no bootstrap credential, `PlayerExecutionContext`, Game Session session, original selection or retained roster reference. The request bound is 4 KiB; unknown fields, noncanonical UUIDs and incomplete targets are invalid. The response echoes the exact entire request and contains at most 100 unique actors ordered by canonical UUID text within 64 KiB. Each actor has its persisted UUID, trimmed control-free display name of at most 100 Unicode code points, and explicit nonnegative `level` sourced from the same eligible `characters` row. The optional wire field must be present even when the actual persisted level is zero; absence is never normalized to zero. + +Entity independently reads the complete current Game Session, sealed publication and World target through its existing Entity-only `GetCanonicalGameplayRosterOwnerRead` client and codec before querying persisted rows, compares the exact reconstructed target with the caller's expected target, and rereads that owner target after the short local projection transaction. Only current visible public-production `SHARED` / `PRESEEDED_ONLY` is supported. A valid supported target may return zero eligible actors; unsupported private, isolated, `PLAYER_CREATED` and `AUTO_PROVISIONED` paths remain explicit obligations and cannot return a fabricated empty success. Malformed input is `INVALID_ARGUMENT`, unsupported or changed preconditions are `FAILED_PRECONDITION`, and unavailable owner or storage reads are `UNAVAILABLE`; failures return no partial projection. This read allocates no actor, selection, snapshot, admission nonce or retention reference and supplies no admission authority or distributed source hold. See [runtime/data limitations](./runtime-and-data.md#account-bootstrap-transient-projection) and the [proof tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#account-bootstrap-persisted-discovery). diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 3ef2440b85..9fb8f7cfce 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -554,3 +554,9 @@ If you change Redis usage for this service, you must read and apply: - [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md) - [FireMUD Redis Lua Patterns](../../system-architecture-redis-lua-patterns.md) - [Redis Operations & Migrations](../../system-architecture-redis-operations.md) + +### Account bootstrap transient projection + +The [Account bootstrap read](./api-contracts.md#account-bootstrap-persisted-actor-discovery) uses one independent five-second read-only repeatable-read owner transaction between two independently authenticated current-target reads. It refuses ambient SQL transactions or synchronization before source access. Both source RPCs run outside SQL; the transaction selects only the exact Account UUID, tenant UUID, playable-state namespace and scope with `OWNER_RESOLVED` identity and no quarantine reason. UUID, name and the existing Entity-owned `characters.level` come from the same selected row; this projection does not introduce mandatory authored RPG state. A missing local namespace enrollment may yield a valid empty roster only after the complete supported current owner target is independently established; the read never inserts enrollment. An existing contradictory enrollment refuses. + +This transient projection shares the canonical actor predicates and bounded UUID ordering with sealed roster reads, while creating no sealed payload or receipt. The post-projection current-target read detects source movement across the local read; it does not hold remote sources or protect a later selection, token issuance or gameplay commit. Account remains responsible for its caller eligibility and future admission revalidation. Current preseeded assignment storage permits one owner-resolved actor per account/tenant/namespace; the read does not widen that write invariant. The finite wire list preserves deterministic handling for any future supported multiple-actor writer. Private, player-created, auto-provisioned and isolated discovery remain unsupported by this local branch, and their target-state obligations remain under [persisted actor and realm-entry identity](#persisted-actor-and-realm-entry-identity). Source and proof status is in the [implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#account-bootstrap-persisted-discovery). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5b63293b6e..ee2f1503db 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -33,6 +33,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-02` (Pacific/Auckland): SpotBugs crashed during Account authentication extraction. - A distinct local JVM failure occurred at 5:06:16am NZDT on 2 November during the 49-file Account authentication extraction: the Temurin 25.0.5+8 SpotBugs worker `2436948` crashed with `SIGSEGV` in `IndexSetIterator::advance_and_next` while C2 compiled `ValueRangeAnalysisFactory.analyze`. The wrapper returned exit 1 without an observed resource-drain stall. Root preserved the fatal and compiler-replay logs in R1430 and reported the occurrence to Overseer. This differs from the earlier Java 21 G1 daemon failure; a common cause is unproven. Next: retain the unchanged targeted SpotBugs retry outcome and compare exact JVM/frame evidence if it recurs; do not treat passing tests as completion of the failed static gate. + - Recurrence on 3 November: public receiving proof346 crashed Temurin 25.0.5+8 worker4180380 during `:common-platform-core:spotbugsTest` with `SIGSEGV` in `PhaseIdealLoop::build_loop_late`. Fatal and replay logs are retained privately in R1430/public-static346-jvm and in the original worktree. That task joins the existing Game Session main SpotBugs198/200 holds pending the Overseer JVM investigation; do not retry it or change JVM options, JDK or host without that investigation’s direction. Other selected enabled checks and documentation pass; the complete static gate remains unqualified. A common cause is unknown. - `2026-11-01` (Pacific/Auckland): Two different repository-network failures interrupted one unchanged CI image build. - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 6b8e888f4c..355b387de8 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -312,3 +312,9 @@ The focused [Ordinary Account UUID copy-carrier test](../../../services/entity-m | Social Groups | Durable communication mutation persistence and duplicate-delivery convergence | Communication persistence and fanout contracts | | Account and Common Security | Account identity, caller scope, gameplay attestation, and authorization inputs | Auth/session and gameplay-attestation helpers | | Automation Scripting | Future effect-producing automation; it is not the authority for item, actor, or communication mutation | Script/event handoff contracts | + +### Account bootstrap persisted discovery + +The manually composed, unregistered Account bootstrap discovery source now has a distinct purpose proto, exact Account workload guard, current-source adapter overload without a fabricated Game Session session, and a read-only persisted projection. It rereads the complete actual Game Session owner target before and after local SQL and preserves actual same-row UUID/name/level. Its contract and currentness limits are owned by [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery) and [runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#account-bootstrap-transient-projection). + +Focused unit and combined PostgreSQL/socket-mTLS test sources cover real typed client/codec/adapter composition, actual Entity/Saga migrations and assignment writer, persisted zero/one actor reads, same-row nonzero and zero levels, account/namespace isolation, quarantine exclusion, unchanged actor/selection/snapshot/retention storage, workload/context refusal, closure/bounds, unsupported scope/policy, unavailable source and source-digest drift across SQL. Upstream Game Session/World/publication bytes and assignment eligibility remain controlled fixtures rather than executed upstream owner stores or production custody. Existing preseeded writer uniqueness prevents a physical many-actor fixture; bounded ordered multiple-response validation is unit source coverage only. Preserved source proof309 passes eight focused units and three combined PostgreSQL/socket-mTLS cases. Actual public receiving compilation342 now passes; focused receiving execution and documentation checks remain pending. These executions retain their source attribution and do not establish a complete upstream chain. This source addition does not qualify production registration, Account consumer settlement, private/player-created/auto-provisioned discovery, admission or activation. 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 c1ab76d5cc..b358156cca 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,7 +16,13 @@ The current billing-owner tuple deliberately rejects unaudited updates. Fixture The same receiving boundary carries the distinct TENANT_OPERATION evidence, Account source/peer-qualified receiver, and World client/mTLS proof. These are unregistered source components, with controlled upstream/PKI limitations. Receiving compilation328 passes. Focused331 executes203Account units, nine shared evidence/transport cases, four actual World→Account mTLS cases and80PostgreSQL cases; its aggregate fails two intent fixtures. Corrected336 passes all20intent cases (including the additional unaudited-update refusal), enabled affected static checks, formatting and documentation. Together these executions establish81unique focused PostgreSQL cases without failures/errors/skips; unchanged passing suites retain331attribution. Fresh-image/runtime and current-head CI/review remain required; controlled sources/PKI do not establish production custody or authenticated transfer. -The existing public WORLDS/REALMS/CHARS, browser/direct JOIN, direct scope and connect-token facade paths temporarily return AUTH_UNAVAILABLE before legacy authority reads; the numeric runtime entitlement endpoint returns ENTITLEMENT_UNAVAILABLE. Complete canonical V2/JOIN/CHARS implementation and all positive compositions remain preserved in the separate public receiving source. This temporary boundary does not complete that work or permit dropping its positive obligations. Ordinary Account authentication, UUID player-bootstrap issuance, profile and retention/deletion protections remain in scope for receiving qualification. Private/ISOLATED/PLAYER_CREATED/AUTO positives, protected target currentness through commit, genuine installation delivery and private FRESH/CLOSED aggregation remain unfinished; registration/issuer/custody/activation holds remain. +The published foundation carrier #3389 deliberately leaves public facade and numeric runtime entitlement paths unavailable; its source-built340 run passes held-edge denial and LOGIN but fails PLAY with ENTITLEMENT_UNAVAILABLE. Authenticated teardown and independently empty resources pass. This is an incomplete runtime qualification, not a passing smoke result. The complete public consumer receiving below restores its own supported canonical compositions; canonical runtime cutover and final functional restoration remain separate obligations. Ordinary UUID identity/profile/retention protections retain their focused proof. + +### Canonical public Account facade receiving + +The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1035 diagnostics and V1037 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). + +Preserved source proof310 passes575selected Account units,318passes312facade units and two actual HTTP→Entity compositions,320passes42App PostgreSQL cases,321passes13first-JOIN cases,324passes22PLAYER_ADMISSION owner plus five shared cases, and335passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving343/345 establish793unique selected unit passes after correcting one obsolete first-only generic proof assertion;344passes109selected physical PostgreSQL/HTTP/composition cases without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main198/200 holds remain. Remaining347static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The source is unpublished and does not close the accepted terminal-recovery Major. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. ### Lifecycle-bound private realm-grant source preparation @@ -32,7 +38,7 @@ The source owner refuses ambient Account SQL and requires a workload-only `Sessi [`AccountPublicBootstrapWorldsOwnerTest`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [`AccountPublicBootstrapEntitlementOwnerTest`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), the [Account target client test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), and the focused [Game Session collection-read](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java) and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java) cover the manually composed discovery source. Proof163/166 executes 165 selected units (17 shared codec, 44 Game Session and 104 Account); proof164/166 executes seven real Account PostgreSQL discovery cases, including successful deterministic filtering, genuine source-head mutation, missing source, expiry, ambiguity, target change and caller-currentness loss. Proof167 qualifies the nullable transaction-definition fixture and Account test static analysis; proof168 adds three real loopback mTLS client cases for exact peer identity, authenticated empty collection and malformed/correlation refusal. These source tests use actual Account DEMO SQL and a controlled complete Game Session response; the loopback mTLS tests use a controlled Game Session server. Neither establishes the whole authenticated source chain or deployment custody. Proof178 passes 189 selected unit/loopback cases and 13 physical cases, with affected static, formatting and documentation checks; the physical cases include the seven discovery cases, three pre-V1028 scope cases and three final-admission composition cases. The latter use a controlled World capture, not a qualified end-to-end World source chain. -The existing public facade is temporarily unavailable during the [canonical billing receiving](#canonical-billing-and-retention-receiving) split. Its complete canonical consumer and positive proof remain preserved for the successor; neither retained numeric billing history nor the separately prepared scope owner supplies a fallback. +The [canonical public receiving](#canonical-public-account-facade-receiving) composes these sources through the existing facade. Absent composition remains unavailable; retained numeric billing history supplies no fallback. Detailed current proof and gaps remain at that receiving owner. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) adds an actual public selector-scope producer over the same complete target and current Account source owners. It preserves genuine membership absence without enrolling a pair, returns current ACTIVE/INACTIVE facts without treating closed enrollment as loss of public visibility, and persists signed canonical UUID V2 scope preimages through the existing Account scope repository. Root's proof176 passes 21 focused signing/orchestration/refusal cases and affected enabled checks. These use real local signing and bootstrap verification with controlled source/transaction inputs; proof177 also passes the three actual pre-V1028 PostgreSQL scope cases alongside the seven existing WORLDS cases (1m20), with enabled affected checks. These retain exact signed UUID/V2 hash/digest/provenance bytes without membership/pair/JOIN/event writes, refuse a real DEMO source-head change, and roll back a real PostgreSQL insert refusal. No facade/default registration, private lifecycle completion, JOIN or admission is established. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 922f3b881c..56e6a9183f 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -78,6 +78,9 @@ message JoinPublicProductionMembershipResponse { uint64 membership_authority_generation = 7; bool replayed = 8; shared.v1.ErrorDetail error = 9; + // Exact current membership flag. A successful membership receipt may be non-admitting; + // this field and success never replace the separate current gameplay admission checks. + bool gameplay_admission_allowed = 10; } // Empty request used to verify that the service is reachable. diff --git a/protos/account/v1/player_admission_entitlement_read.proto b/protos/account/v1/player_admission_entitlement_read.proto new file mode 100644 index 0000000000..ee5d174bb6 --- /dev/null +++ b/protos/account/v1/player_admission_entitlement_read.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; + +package account.v1; + +import "game-session/v1/canonical_gameplay_admission_decision_read.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Manually composed Account read for exact same-namespace Game Session over workload mTLS. +// This point-in-time PLAYER_ADMISSION value supplies neither capacity nor a later World hold. +service AccountPlayerAdmissionEntitlementReadService { + rpc ReadPlayerAdmissionEntitlement(ReadPlayerAdmissionEntitlementRequest) + returns (ReadPlayerAdmissionEntitlementResponse); +} + +// Comparison selectors only. Account verifies the credential subject and retained scope, and +// selects the current paid/demo source itself. Repeated members each require exactly one value. +message PlayerAdmissionEntitlementReadSelectors { + repeated uint32 schema_version = 1; + repeated game_session.v1.ResolvePublishedRealmAdmissionTargetRequest target = 2; + repeated string connect_scope_id = 3; +} + +// Credential travels only on this exact trusted mTLS method and must never be logged or persisted. +message ReadPlayerAdmissionEntitlementRequest { + repeated PlayerAdmissionEntitlementReadSelectors selectors = 1; + repeated string initial_login_jwt = 2; +} + +// Echo only selectors, never the presented credential. Evidence is exact bounded RFC 8785 UTF-8. +message ReadPlayerAdmissionEntitlementResponse { + repeated PlayerAdmissionEntitlementReadSelectors request = 1; + repeated bytes canonical_evidence = 2; +} diff --git a/protos/entity-management/v1/account_bootstrap_roster_read.proto b/protos/entity-management/v1/account_bootstrap_roster_read.proto new file mode 100644 index 0000000000..9e1a9dacbd --- /dev/null +++ b/protos/entity-management/v1/account_bootstrap_roster_read.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package entity_management.v1; + +import "entity-management/v1/entity_management_service.proto"; + +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +// Manually composed and unregistered non-admitting Account discovery. This transient +// projection creates no original selection, roster snapshot, retention or session. +service AccountBootstrapRosterReadService { + // Exact same-workload-namespace Account mTLS is required before request decoding. + // Only independently current public-production SHARED PRESEEDED_ONLY targets are + // supported. A valid empty persisted roster succeeds; unsupported, stale and + // unavailable sources never become an empty success. Failures use non-OK status. + rpc ReadAccountBootstrapRoster(AccountBootstrapRosterReadRequest) + returns (AccountBootstrapRosterReadResponse); +} + +message AccountBootstrapRosterReadRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + string target_namespace = 3; + CanonicalGameplayRosterTarget expected_target = 4; +} + +message AccountBootstrapRosterReadResponse { + // Complete exact request echo, including every source digest and target counter. + AccountBootstrapRosterReadRequest request = 1; + // At most 100 persisted eligible actors, ordered by canonical UUID text. + repeated AccountBootstrapRosterActor actors = 2; +} + +message AccountBootstrapRosterActor { + string character_uuid = 1; + string display_name = 2; + // Existing Entity-owned persisted level from the same eligible actor row, including real zero. + optional int32 level = 3; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 8eb626f23b..d7d9bdbcfd 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -92,6 +92,11 @@ dependencies { add("integrationTestCompileOnly", libs.spotbugs.annotations) integrationTestImplementation(project(path = ":game-session-service", configuration = "gameSessionClassesProof")) integrationTestImplementation(project(path = ":entity-management-service", configuration = "entityClassesProof")) + // Share canonical bootstrap proof values without importing Entity application resources. + val entityBootstrapProof = testFixtures(project(":entity-management-service")) + as org.gradle.api.artifacts.ModuleDependency + entityBootstrapProof.isTransitive = false + integrationTestImplementation(entityBootstrapProof) integrationTestImplementation(testFixtures(project(":common-test-support"))) integrationTestImplementation(project(":social-groups-service")) integrationTestImplementation(testFixtures(project(":account-service"))) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java new file mode 100644 index 0000000000..605fa05d04 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Manually composed Entity persisted discovery read. No session, selection or admission is minted. + */ +public final class AccountBootstrapRosterReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceBlockingStub> { + public static final int MAX_REQUEST_BYTES = 4096; + public static final int MAX_RESPONSE_BYTES = 64 * 1024; + public static final int MAX_ACTORS = 100; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final String namespace; + + public AccountBootstrapRosterReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account bootstrap Entity discovery"), + channels, + AccountBootstrapRosterReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + public void init() throws IOException { + requireNoAmbientSql("Bootstrap Entity discovery initialization refuses ambient SQL"); + initOnce( + "Bootstrap Entity discovery client is closed", + "Bootstrap Entity discovery client is not initialized"); + } + + /** + * Reads an exact independently resolved target; scope/caller authentication remains with Account. + */ + public List read(UUID requestId, UUID accountId, PublishedRealmEvidence published) { + requireNoAmbientSql("Bootstrap Entity discovery refuses ambient SQL"); + // This stub has no GrpcClientAuth/customizer: local browser SessionContext is preserved, + // and only the Account workload certificate authenticates this purpose-specific read. + requireUuid(requestId); + requireUuid(accountId); + Objects.requireNonNull(published); + if (!accountId.equals(published.selector().canonicalAccountUuid()) + || !namespace.equals(published.selector().targetNamespace())) { + throw new IllegalArgumentException("Bootstrap Entity discovery caller/namespace mismatch"); + } + AccountBootstrapRosterReadRequest request = + AccountBootstrapRosterReadRequest.newBuilder() + .setRequestUuid(requestId.toString()) + .setCanonicalAccountUuid(accountId.toString()) + .setTargetNamespace(namespace) + .setExpectedTarget(expectedTarget(published)) + .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Bootstrap Entity request exceeds its bound"); + } + var response = + requireInitializedStub("Bootstrap Entity discovery client is not initialized") + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .readAccountBootstrapRoster(request); + if (!response.getUnknownFields().asMap().isEmpty() + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.hasRequest() + || !request.equals(response.getRequest()) + || response.getActorsCount() > MAX_ACTORS) { + throw new IllegalStateException( + "Entity bootstrap discovery response is malformed or mismatched"); + } + List actors = new ArrayList<>(response.getActorsCount()); + String previous = null; + for (var actor : response.getActorsList()) { + UUID id = parseUuid(actor.getCharacterUuid()); + if (!actor.getUnknownFields().asMap().isEmpty() + || !actor.hasLevel() + || (previous != null && previous.compareTo(actor.getCharacterUuid()) >= 0)) { + throw new IllegalStateException( + "Entity bootstrap discovery actors are duplicated or unordered"); + } + actors.add(new Actor(id, actor.getDisplayName(), actor.getLevel())); + previous = actor.getCharacterUuid(); + } + return List.copyOf(actors); + } + + private CanonicalGameplayRosterTarget expectedTarget(PublishedRealmEvidence published) { + var target = published.currentTarget(); + var source = published.sourceEvidence(); + var policy = source.selectedPolicyEvidence(); + var policySet = source.publishedPolicySetEvidence(); + policySet.requireValidDigest(); + policy.requireValidDigest(policySet); + if (!namespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) { + throw new IllegalArgumentException( + "Bootstrap Entity discovery supports public SHARED PRESEEDED_ONLY targets"); + } + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.canonicalGameInstanceId().toString()) + .setCatalogRevision(target.catalogRevision()) + .setPointerVersion(target.pointerVersion()) + .setActiveWorldEpoch(target.activeWorldEpoch()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setPublishedPolicyDigest(rawDigest(policy.policyDigest())) + .setPublishedReleaseBundleRef(policySet.publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(target.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(rawDigest(target.ownerProofDigest())) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + } + + private static String rawDigest(String prefixed) { + if (prefixed == null || !prefixed.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical published source digest is malformed"); + } + return prefixed.substring(7); + } + + private static UUID parseUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) + throw new IllegalStateException("Canonical actor UUID required"); + return id; + } + + private static void requireUuid(UUID value) { + if (value == null || NIL_UUID.equals(value)) + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return AccountBootstrapRosterReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + public record Actor(UUID characterId, String displayName, int level) { + public Actor { + requireUuid(characterId); + if (level < 0 + || displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.codePointCount(0, displayName.length()) > 100 + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Canonical actor display name required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java index 239ad9298d..66d8c25812 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java @@ -1,20 +1,26 @@ package net.firedevops.firemud.accountservice.dto; -/** Realm visible to a bootstrap-authenticated first-party client. */ +import java.util.UUID; + +/** Public realm selector evidence; its retained scope grants neither entry nor character access. */ public record BootstrapRealmDto( String worldSlug, String realmSlug, - String realmId, + UUID realmId, String displayName, - long tenantId, - long gameInstanceId, + UUID tenantId, + UUID gameInstanceId, long pointerVersion, long catalogRevision, - String playableStateNamespaceId, + UUID playableStateNamespaceId, String playableStateScope, - boolean requiresCharacterSelection, String stateScope, String characterCreationPolicy, String evaluatedAt, String connectScopeExpiresAt, - String connectScopeId) {} + String connectScopeId) { + @Override + public String toString() { + return "BootstrapRealmDto[nonadmitting, connectScopeId=]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java index 7c779d3e43..433ace8057 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java @@ -60,6 +60,11 @@ public record CanonicalJoinScopeV2( connectScopeExpiresAt = requireUtcRfc3339("connectScopeExpiresAt", connectScopeExpiresAt); } + @Override + public String toString() { + return "CanonicalJoinScopeV2[connectScopeId=]"; + } + private static UUID requireNonNilUuid(String field, UUID value) { if (value == null || NIL_UUID.equals(value)) { throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java index 2638dc9cfb..c0c0e8fa2d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java @@ -4,11 +4,11 @@ /** Parsed scope data from a verified Game Session mTLS call, never an independent capability. */ public record DirectTextCallerContext( - long accountId, - long tenantId, + UUID accountId, + UUID tenantId, UUID realmId, - String playableStateNamespaceId, + UUID playableStateNamespaceId, String playableStateScope, - long gameInstanceId, + UUID gameInstanceId, String sessionId, String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java index b4273bf5b5..e593ee852f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java @@ -6,12 +6,12 @@ * Game Session's complete selected-target evidence, re-resolved by Account before scope issuance. */ public record DirectTextJoinTarget( - long tenantId, + UUID tenantId, UUID realmId, String worldSlug, String realmSlug, - String playableStateNamespaceId, + UUID playableStateNamespaceId, String playableStateScope, - long gameInstanceId, + UUID gameInstanceId, long catalogRevision, long pointerVersion) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java index 803188b178..8140d09562 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java @@ -1,12 +1,18 @@ package net.firedevops.firemud.accountservice.dto; -/** Durable explicit-JOIN outcome; a failure is returned so its receipt can commit first. */ +import java.util.UUID; + +/** + * Durable membership-operation outcome. Success preserves the exact membership admission flag; it + * is not a gameplay admission grant. A failure is returned so its receipt can commit first. + */ public record JoinPublicProductionResult( boolean success, String outcomeCode, String accountId, - long tenantId, + UUID tenantId, long membershipId, long membershipVersion, long membershipAuthorityGeneration, + boolean gameplayAdmissionAllowed, boolean replayed) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index dc5ae14240..8977650524 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -9,6 +9,7 @@ import java.time.Instant; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; @@ -30,6 +31,17 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountJoinOperationRepository { + private static final Set DEFINITIVE_FAILURES = + Set.of( + "CONNECT_SCOPE_INVALID", + "CONNECT_SCOPE_MISMATCH", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "TENANT_BILLING_BLOCKED", + "IDEMPOTENCY_CONFLICT", + "MEMBERSHIP_RECONCILIATION_REQUIRED", + "REALM_UNAVAILABLE"); + private static final Set RETRYABLE_FAILURES = + Set.of("AUTH_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"); private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final String CANONICAL_SELECT_COLUMNS = "SELECT request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " @@ -252,8 +264,30 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( if (operation.requestDigest() != null) { requireCanonicalPolicyMatch(operation, requestDigest, allowPublicJoin, entitlementVersion); - return operation; + if (!"PENDING".equals(operation.status()) + || ("AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() == null)) return operation; + int recovered = + dsl.execute( + "UPDATE account_join_operations SET last_attempt_authority_availability = 'AVAILABLE', " + + "last_attempt_failure_code = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 AND status = 'PENDING'", + requestId); + if (recovered != 1) + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN attempt recovery changed"); + CanonicalJoinOperationEvidence readback = + readCanonicalEvidenceByRequestId(requestId, false).orElseThrow(); + requireCanonicalIntentMatch(readback, requestId, callerBinding, intentDigest, scopeEvidence); + requireCanonicalPolicyMatch(readback, requestDigest, allowPublicJoin, entitlementVersion); + if (!"AVAILABLE".equals(readback.lastAttemptAuthorityAvailability()) + || readback.lastAttemptFailureCode() != null) + throw new IllegalStateException("Canonical JOIN recovered attempt readback differs"); + return readback; } + if (!"PENDING".equals(operation.status())) + throw new CanonicalJoinOperationConflictException( + "Terminal canonical JOIN cannot acquire policy evidence"); int updated = dsl.execute( @@ -282,17 +316,34 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( return committed; } - /** Records unavailable policy without creating a policy result, entitlement version or digest. */ + /** Records policy unavailability without downgrading an already-bound available policy. */ @Transactional(propagation = Propagation.MANDATORY) public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( String requestId, CanonicalJoinScopeV2 scope, String callerBinding, String failureCode) { + return recordCanonicalAttemptFailure( + requestId, scope, callerBinding, "UNAVAILABLE", failureCode); + } + + /** + * Records only a retryable PENDING attempt. Bound policy bytes are immutable; an unbound intent + * retains no policy/version/digest. This journal method supplies no source authentication. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence recordCanonicalAttemptFailure( + String requestId, + CanonicalJoinScopeV2 scope, + String callerBinding, + String authorityAvailability, + String failureCode) { requireWritableOwnerTransaction(); requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); - if (failureCode == null || failureCode.isBlank() || failureCode.length() > 64) { + if (!("UNAVAILABLE".equals(authorityAvailability) + || "NOT_EVALUATED".equals(authorityAvailability)) + || failureCode == null + || !RETRYABLE_FAILURES.contains(failureCode)) throw new IllegalArgumentException( - "JOIN attempt failure code must contain 1 to 64 characters"); - } + "Canonical JOIN retryable attempt classification is invalid"); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); CanonicalJoinOperationEvidence operation = @@ -301,42 +352,91 @@ public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( () -> new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); - if (operation.requestDigest() != null) { + if (!"PENDING".equals(operation.status())) throw new CanonicalJoinOperationConflictException( - "Available canonical JOIN policy evidence cannot be downgraded"); - } - + "Terminal canonical JOIN cannot record another attempt"); int updated = dsl.execute( - "UPDATE account_join_operations SET entitlement_authority_availability = 'UNAVAILABLE', " - + "last_attempt_authority_availability = 'UNAVAILABLE', " - + "last_attempt_failure_code = ?, updated_at = CURRENT_TIMESTAMP " - + "WHERE request_id = ? AND operation_representation_version = 2 " - + "AND status = 'PENDING' AND request_digest IS NULL", + "UPDATE account_join_operations SET entitlement_authority_availability = " + + "CASE WHEN request_digest IS NULL THEN ? ELSE entitlement_authority_availability END, " + + "last_attempt_authority_availability = ?, last_attempt_failure_code = ?, " + + "updated_at = CURRENT_TIMESTAMP WHERE request_id = ? " + + "AND operation_representation_version = 2 AND status = 'PENDING'", + authorityAvailability, + authorityAvailability, failureCode, requestId); - if (updated != 1) { - throw new CanonicalJoinOperationConflictException( - "Canonical JOIN operation changed while recording policy unavailability"); - } + if (updated != 1) + throw new CanonicalJoinOperationConflictException("Canonical JOIN attempt changed"); + CanonicalJoinOperationEvidence readback = + readCanonicalEvidenceByRequestId(requestId, false).orElseThrow(); + requireCanonicalIntentMatch(readback, requestId, callerBinding, intentDigest, scopeEvidence); + if (!Objects.equals(operation.requestDigest(), readback.requestDigest()) + || !Objects.equals(operation.requestDigestVersion(), readback.requestDigestVersion()) + || !Objects.equals(operation.entitlementVersion(), readback.entitlementVersion()) + || !Objects.equals(operation.allowPublicJoin(), readback.allowPublicJoin()) + || !authorityAvailability.equals(readback.lastAttemptAuthorityAvailability()) + || !failureCode.equals(readback.lastAttemptFailureCode()) + || (operation.requestDigest() != null + && !operation + .entitlementAuthorityAvailability() + .equals(readback.entitlementAuthorityAvailability()))) + throw new IllegalStateException( + "Canonical JOIN attempt readback changed policy or diagnostics"); + return readback; + } - CanonicalJoinOperationEvidence committed = - readCanonicalEvidenceByRequestId(requestId, false) + /** + * Persists or exactly replays a definitive, noncommitting failure with the original scope/intent + * and optional original policy. Replay performs no UPDATE. Caller/target/current-authority checks + * belong to the public adapter, not this persistence receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence finishCanonicalFailure( + String requestId, CanonicalJoinScopeV2 scope, String callerBinding, String outcome) { + requireWritableOwnerTransaction(); + requireCanonicalOperationInput(requestId, callerBinding); + Objects.requireNonNull(scope, "Canonical JOIN scope is required"); + if (outcome == null || !DEFINITIVE_FAILURES.contains(outcome)) + throw new IllegalArgumentException( + "Canonical JOIN definitive failure classification is invalid"); + CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) .orElseThrow( () -> - new IllegalStateException( - "Canonical JOIN unavailable-attempt readback is absent")); - requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); - if (!"UNAVAILABLE".equals(committed.entitlementAuthorityAvailability()) - || committed.entitlementVersion() != null - || committed.allowPublicJoin() != null - || committed.requestDigestVersion() != null - || committed.requestDigest() != null - || !failureCode.equals(committed.lastAttemptFailureCode())) { - throw new IllegalStateException( - "Canonical JOIN unavailable attempt readback contains policy evidence"); - } - return committed; + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); + if ("FAILED".equals(operation.status()) && outcome.equals(operation.outcome())) + return operation; + if (!"PENDING".equals(operation.status())) + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN terminal outcome conflicts"); + int updated = + dsl.execute( + "UPDATE account_join_operations SET status = 'FAILED', outcome = ?, " + + "entitlement_authority_availability = CASE WHEN request_digest IS NULL " + + "THEN 'NOT_EVALUATED' ELSE entitlement_authority_availability END, " + + "last_attempt_authority_availability = CASE WHEN request_digest IS NULL " + + "THEN 'NOT_EVALUATED' ELSE 'AVAILABLE' END, last_attempt_failure_code = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE request_id = ? " + + "AND operation_representation_version = 2 AND status = 'PENDING'", + outcome, + requestId); + if (updated != 1) + throw new CanonicalJoinOperationConflictException("Canonical JOIN failure changed"); + CanonicalJoinOperationEvidence readback = + readCanonicalEvidenceByRequestId(requestId, false).orElseThrow(); + requireCanonicalIntentMatch(readback, requestId, callerBinding, intentDigest, scopeEvidence); + if (!"FAILED".equals(readback.status()) + || !outcome.equals(readback.outcome()) + || !Objects.equals(operation.requestDigest(), readback.requestDigest()) + || !Objects.equals(operation.requestDigestVersion(), readback.requestDigestVersion()) + || !Objects.equals(operation.entitlementVersion(), readback.entitlementVersion()) + || !Objects.equals(operation.allowPublicJoin(), readback.allowPublicJoin())) + throw new IllegalStateException("Canonical JOIN failed receipt readback differs"); + return readback; } /** @@ -350,29 +450,55 @@ public CanonicalJoinOperationEvidence commitCanonicalFirstJoin( CanonicalJoinScopeV2 scope, String callerBinding, CanonicalJoinTerminalProof proof) { + if (proof.eventSequence() != 1L + || proof.membershipVersion() != 2L + || proof.membershipAuthorityGeneration() != 1L + || proof.auditEventId() == null) { + throw new IllegalArgumentException("Exact first-JOIN terminal proof required"); + } + return commitCanonicalJoin(requestId, scope, callerBinding, "JOINED", proof); + } + + /** Persists the exact current ACTIVE snapshot or the same-transaction restore terminal. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence commitCanonicalJoin( + String requestId, + CanonicalJoinScopeV2 scope, + String callerBinding, + String outcome, + CanonicalJoinTerminalProof proof) { requireWritableOwnerTransaction(); requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); Objects.requireNonNull(proof, "Canonical first-JOIN terminal proof is required"); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + boolean publicJoin = Boolean.TRUE.equals(operation.allowPublicJoin()); + if ("JOINED".equals(outcome) && !publicJoin) { + throw new CanonicalJoinOperationConflictException( + "Transition JOIN requires positive public policy"); + } String requestDigest = AccountJoinDigest.requestV2( scope, callerBinding, EntitlementAvailabilityV2.AVAILABLE, - true, + publicJoin, proof.entitlementVersion()); - CanonicalJoinOperationEvidence operation = - lockCanonicalEvidenceByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); - requireCanonicalPolicyMatch(operation, requestDigest, true, proof.entitlementVersion()); + requireCanonicalPolicyMatch(operation, requestDigest, publicJoin, proof.entitlementVersion()); requireTerminalProofScope(proof, requestId, scope, operation); + if (!Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome) + || ("JOINED".equals(outcome) != (proof.auditEventId() != null))) { + throw new CanonicalJoinOperationConflictException("Canonical JOIN outcome/proof conflict"); + } if ("COMMITTED".equals(operation.status())) { - if (!"JOINED".equals(operation.outcome()) + if (!outcome.equals(operation.outcome()) || !Objects.equals(operation.terminalProof(), proof)) { throw new CanonicalJoinOperationConflictException( "Canonical JOIN request ID conflicts with its committed receipt"); @@ -386,27 +512,31 @@ public CanonicalJoinOperationEvidence commitCanonicalFirstJoin( int updated = dsl.execute( - "UPDATE account_join_operations SET status = 'COMMITTED', outcome = 'JOINED', " - + "membership_id = ?, outcome_membership_version = 2, " - + "outcome_membership_authority_generation = 1, " + "UPDATE account_join_operations SET status = 'COMMITTED', outcome = ?, " + + "membership_id = ?, outcome_membership_version = ?, " + + "outcome_membership_authority_generation = ?, " + "membership_authority_outbox_stream_key = ?, " + "membership_authority_outbox_sequence = ?, " + "membership_authority_event_id = ?, membership_authority_event_digest = ?, " + "join_audit_event_id = ?, join_audit_payload_digest = ?, " + "join_audit_occurred_at = ?, last_attempt_failure_code = NULL, " + + "last_attempt_authority_availability = 'AVAILABLE', " + "updated_at = CURRENT_TIMESTAMP " + "WHERE request_id = ? AND operation_representation_version = 2 " + "AND account_uuid = ? AND tenant_uuid = ? " + "AND verified_caller_binding = ? AND intent_digest = ? " + "AND request_digest = ? AND status = 'PENDING'", + outcome, proof.membershipId(), + proof.membershipVersion(), + proof.membershipAuthorityGeneration(), proof.eventStreamKey(), proof.eventSequence(), proof.eventId(), proof.eventDigest(), proof.auditEventId(), proof.auditPayloadDigest(), - toLocalDateTime(proof.auditOccurredAt()), + proof.auditOccurredAt() == null ? null : toLocalDateTime(proof.auditOccurredAt()), requestId, scope.accountId(), scope.tenantId(), @@ -423,9 +553,9 @@ public CanonicalJoinOperationEvidence commitCanonicalFirstJoin( .orElseThrow( () -> new IllegalStateException("Canonical JOIN receipt readback is absent")); requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); - requireCanonicalPolicyMatch(committed, requestDigest, true, proof.entitlementVersion()); + requireCanonicalPolicyMatch(committed, requestDigest, publicJoin, proof.entitlementVersion()); if (!"COMMITTED".equals(committed.status()) - || !"JOINED".equals(committed.outcome()) + || !outcome.equals(committed.outcome()) || !Objects.equals(committed.terminalProof(), proof)) { throw new IllegalStateException("Canonical JOIN receipt readback differs from its proof"); } @@ -649,6 +779,20 @@ private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( Long membershipAuthorityGeneration = row.get("outcome_membership_authority_generation", Long.class); CanonicalJoinTerminalProof terminalProof = null; + if (!"COMMITTED".equals(status)) { + for (String column : + Set.of( + "membership_authority_outbox_stream_key", + "membership_authority_outbox_sequence", + "membership_authority_event_id", + "membership_authority_event_digest", + "join_audit_event_id", + "join_audit_payload_digest", + "join_audit_occurred_at")) { + if (row.get(column) != null) + throw new IllegalStateException("Noncommitting canonical JOIN carries success proof"); + } + } if ("COMMITTED".equals(status)) { terminalProof = new CanonicalJoinTerminalProof( @@ -656,9 +800,12 @@ private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( required(row, "membership_authority_outbox_sequence", Long.class), required(row, "membership_authority_event_id", String.class), required(row, "membership_authority_event_digest", String.class), - required(row, "join_audit_event_id", UUID.class), - required(row, "join_audit_payload_digest", String.class), - toInstant(required(row, "join_audit_occurred_at", java.time.LocalDateTime.class)), + row.get("join_audit_event_id", UUID.class), + row.get("join_audit_payload_digest", String.class), + row.get("join_audit_occurred_at") == null + ? null + : toInstant( + required(row, "join_audit_occurred_at", java.time.LocalDateTime.class)), required(row, "entitlement_version", Long.class), required(row, "membership_id", Long.class), required(row, "outcome_membership_version", Long.class), @@ -703,8 +850,7 @@ private static void requireTerminalProofScope( ("account-join-audit/v1:" + requestId) .getBytes(java.nio.charset.StandardCharsets.UTF_8)); if (!expectedStreamKey.equals(proof.eventStreamKey()) - || proof.eventSequence() != 1L - || !expectedAuditEventId.equals(proof.auditEventId()) + || (proof.auditEventId() != null && !expectedAuditEventId.equals(proof.auditEventId())) || !Objects.equals(operation.entitlementVersion(), proof.entitlementVersion())) { throw new CanonicalJoinOperationConflictException( "Canonical JOIN terminal proof differs from its exact request and owner scope"); @@ -879,7 +1025,7 @@ public CanonicalJoinOperationEvidence( || intentDigest == null || entitlementAuthorityAvailability == null || lastAttemptAuthorityAvailability == null - || (!"PENDING".equals(status) && !"COMMITTED".equals(status)) + || (!"PENDING".equals(status) && !"COMMITTED".equals(status) && !"FAILED".equals(status)) || callerBoundAuthorityInvalidated || scopeEvidence == null || scopeEvidence.privateAccountId() != privateAccountId @@ -887,22 +1033,27 @@ public CanonicalJoinOperationEvidence( || !connectScopeDigest.equals(scopeEvidence.scopeDigest())) { throw new IllegalArgumentException("Canonical JOIN operation evidence is incomplete"); } - if ("PENDING".equals(status) - ? outcome != null + if (!"COMMITTED".equals(status) + ? ("PENDING".equals(status) + ? outcome != null + : outcome == null || !DEFINITIVE_FAILURES.contains(outcome)) || membershipId != null || membershipVersion != null || membershipAuthorityGeneration != null || terminalProof != null - : !"JOINED".equals(outcome) + : !Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome) || membershipId == null || membershipId <= 0L - || !Long.valueOf(2L).equals(membershipVersion) - || !Long.valueOf(1L).equals(membershipAuthorityGeneration) + || membershipVersion == null + || membershipVersion <= 0L + || membershipAuthorityGeneration == null + || membershipAuthorityGeneration <= 0L || terminalProof == null || membershipId.longValue() != terminalProof.membershipId() || membershipVersion.longValue() != terminalProof.membershipVersion() || membershipAuthorityGeneration.longValue() - != terminalProof.membershipAuthorityGeneration()) { + != terminalProof.membershipAuthorityGeneration() + || ("JOINED".equals(outcome) != (terminalProof.auditEventId() != null))) { throw new IllegalArgumentException("Canonical JOIN terminal evidence is inconsistent"); } requireSha256(scopeTokenHash, "Canonical JOIN scope token hash"); @@ -913,9 +1064,7 @@ public CanonicalJoinOperationEvidence( || entitlementVersion == null || entitlementVersion <= 0L || !Integer.valueOf(2).equals(requestDigestVersion) - || requestDigest == null - || lastAttemptFailureCode != null - || !"AVAILABLE".equals(lastAttemptAuthorityAvailability)) { + || requestDigest == null) { throw new IllegalArgumentException( "Canonical JOIN available policy evidence is incomplete"); } @@ -925,19 +1074,26 @@ public CanonicalJoinOperationEvidence( && allowPublicJoin == null && entitlementVersion == null && requestDigestVersion == null - && requestDigest == null - && (("UNAVAILABLE".equals(entitlementAuthorityAvailability) - && "UNAVAILABLE".equals(lastAttemptAuthorityAvailability) - && lastAttemptFailureCode != null - && !lastAttemptFailureCode.isBlank()) - || ("NOT_EVALUATED".equals(entitlementAuthorityAvailability) - && "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability) - && lastAttemptFailureCode == null))) { - // No policy outcome has been fabricated for this PENDING intent. + && requestDigest == null) { + if (!entitlementAuthorityAvailability.equals(lastAttemptAuthorityAvailability)) + throw new IllegalArgumentException("Unbound canonical JOIN attempt availability differs"); } else { throw new IllegalArgumentException( "Canonical JOIN policy-attempt evidence is inconsistent"); } + boolean retryableAttempt = + "PENDING".equals(status) + && ("UNAVAILABLE".equals(lastAttemptAuthorityAvailability) + || "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability)) + && lastAttemptFailureCode != null + && RETRYABLE_FAILURES.contains(lastAttemptFailureCode); + boolean cleanAttempt = + lastAttemptFailureCode == null + && (requestDigest == null + ? "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability) + : "AVAILABLE".equals(lastAttemptAuthorityAvailability)); + if (!retryableAttempt && !cleanAttempt) + throw new IllegalArgumentException("Canonical JOIN attempt diagnostics are inconsistent"); } } @@ -957,17 +1113,18 @@ public record CanonicalJoinTerminalProof( if (eventStreamKey == null || eventId == null || eventId.isBlank() - || eventSequence != 1L - || auditEventId == null - || auditOccurredAt == null + || eventSequence <= 0L + || ((auditEventId == null) != (auditOccurredAt == null)) + || ((auditEventId == null) != (auditPayloadDigest == null)) || entitlementVersion <= 0L || membershipId <= 0L - || membershipVersion != 2L - || membershipAuthorityGeneration != 1L) { + || membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L) { throw new IllegalArgumentException("Canonical first-JOIN terminal proof is incomplete"); } requireSha256(eventDigest, "Canonical membership event digest"); - requireSha256(auditPayloadDigest, "Canonical JOIN audit payload digest"); + if (auditPayloadDigest != null) + requireSha256(auditPayloadDigest, "Canonical JOIN audit payload digest"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java index b1e96d9f72..3a5e3016e4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -218,6 +218,95 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra return advanced; } + /** Advances an existing positive pair after its exact restored membership event was appended. */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority commitRestore(PairAuthority expected, PairTransition transition) { + requireOwnerWriteTransaction(); + Objects.requireNonNull(expected); + Objects.requireNonNull(transition); + requireFreshProvenance(expected.provenance()); + long nextSequence = increment(expected.eventSequence(), "membership event sequence"); + long nextVersion = increment(expected.membershipVersion(), "membership version"); + if (!expected.membershipExists() + || expected.eventSequence() <= 0L + || !transition.membershipExists() + || transition.eventSequence() != nextSequence + || transition.callerBoundAuthorityInvalidated() + || !expected.equals( + readForUpdate(expected.accountUuid(), expected.tenantUuid()).orElseThrow())) { + throw new IllegalStateException("Restore requires the exact current positive pair"); + } + Record ownerEvidence = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_authority_outbox_events next_event " + + "JOIN account_authority_outbox_streams stream USING (outbox_stream_key) " + + "JOIN account_authority_outbox_events prior_event USING (outbox_stream_key) " + + "JOIN accounts account ON account.account_uuid = ? " + + "JOIN account_tenant_membership member ON member.account_id = account.id AND member.tenant_uuid = ? " + + "WHERE next_event.outbox_stream_key = ? AND next_event.outbox_sequence = ? " + + "AND next_event.event_id = ? AND next_event.event_digest = ? AND stream.last_sequence = ? " + + "AND prior_event.outbox_sequence = ? AND prior_event.event_id = ? AND prior_event.event_digest = ? " + + "AND convert_from(prior_event.payload, 'UTF8')::JSONB ->> 'membershipLifecycleState' = 'INACTIVE' " + + "AND member.lifecycle_state = 'ACTIVE' AND member.gameplay_admission_allowed IS TRUE " + + "AND member.membership_version = ? AND member.membership_authority_generation = ?)", + expected.accountUuid(), + expected.tenantUuid(), + "account:auth-authority:v1:membership/" + + expected.accountUuid() + + "/" + + expected.tenantUuid(), + nextSequence, + transition.eventId(), + transition.eventDigest(), + nextSequence, + expected.eventSequence(), + expected.eventId(), + expected.eventDigest(), + nextVersion, + expected.membershipAuthorityGeneration()); + if (ownerEvidence == null || !Boolean.TRUE.equals(ownerEvidence.get(0, Boolean.class))) { + throw new IllegalStateException( + "Restore pair requires actual current membership and event evidence"); + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET membership_version = ?, last_event_sequence = ?, " + + "last_event_id = ?, last_event_digest = ?, last_transition_invalidated = FALSE " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND membership_exists IS TRUE " + + "AND membership_version = ? AND membership_authority_generation = ? " + + "AND last_event_sequence = ? AND last_event_id = ? AND last_event_digest = ?", + nextVersion, + nextSequence, + transition.eventId(), + transition.eventDigest(), + expected.accountUuid(), + expected.tenantUuid(), + expected.membershipVersion(), + expected.membershipAuthorityGeneration(), + expected.eventSequence(), + expected.eventId(), + expected.eventDigest()); + if (changed != 1) throw new IllegalStateException("Restore pair compare-and-advance failed"); + PairAuthority actual = + readForUpdate(expected.accountUuid(), expected.tenantUuid()).orElseThrow(); + PairAuthority required = + new PairAuthority( + expected.accountUuid(), + expected.tenantUuid(), + expected.provenance(), + true, + nextVersion, + expected.membershipAuthorityGeneration(), + nextSequence, + transition.eventId(), + transition.eventDigest(), + false); + if (!required.equals(actual)) throw new IllegalStateException("Restore pair readback differs"); + return actual; + } + private static void requireScope(UUID accountUuid, UUID tenantUuid) { if (accountUuid == null || tenantUuid == null || isNil(accountUuid) || isNil(tenantUuid)) { throw new IllegalArgumentException("Canonical non-nil Account and tenant UUIDs are required"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 6618c17601..f5fac1625f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -294,6 +294,51 @@ public AccountTenantMembership createFreshMembershipForJoin(UUID accountUuid, UU return readback; } + /** Stages an INACTIVE restore; its event, pair and terminal receipt must commit atomically. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountTenantMembership restoreFreshMembershipForJoin( + UUID accountUuid, UUID tenantUuid, AccountTenantMembership expected) { + requireOwnerWriteTransaction(); + AccountTenantMembership current = + findFreshMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow(() -> new IllegalStateException("Restore membership is absent")); + if (expected == null + || !Objects.equals(current.getId(), expected.getId()) + || !"INACTIVE".equals(current.getLifecycleState()) + || current.getMembershipVersion() != expected.getMembershipVersion() + || current.getMembershipAuthorityGeneration() + != expected.getMembershipAuthorityGeneration()) { + throw new IllegalStateException("Restore membership changed from its locked snapshot"); + } + long next = increment(current.getMembershipVersion(), "membership version"); + int changed = + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'ACTIVE', " + + "gameplay_admission_allowed = TRUE, membership_version = ?, " + + "authority_provenance = 'EXPLICIT_JOIN' WHERE id = ? AND account_id = ? " + + "AND tenant_id IS NULL AND tenant_uuid = ? AND lifecycle_state = 'INACTIVE' " + + "AND membership_version = ? AND membership_authority_generation = ?", + next, + current.getId(), + current.getAccount().getId(), + tenantUuid, + current.getMembershipVersion(), + current.getMembershipAuthorityGeneration()); + if (changed != 1) + throw new IllegalStateException("Restore membership compare-and-advance failed"); + AccountTenantMembership restored = + findCanonicalMembershipForUpdate(accountUuid, tenantUuid).orElseThrow(); + if (!"ACTIVE".equals(restored.getLifecycleState()) + || !restored.isGameplayAdmissionAllowed() + || restored.getMembershipVersion() != next + || restored.getMembershipAuthorityGeneration() != current.getMembershipAuthorityGeneration() + || !Objects.equals(restored.getId(), current.getId()) + || !"EXPLICIT_JOIN".equals(restored.getAuthorityProvenance())) { + throw new IllegalStateException("Restore membership readback differs"); + } + return restored; + } + /** Account-fenced absence enrollment for the fresh creator owner; creates no membership. */ @Transactional(propagation = Propagation.MANDATORY) public PairAuthority prepareFreshCreatorAbsence(UUID accountUuid, UUID tenantUuid) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java new file mode 100644 index 0000000000..d4839ed5e5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Exact method/Game Session gate deriving its private assertion from transport TLS, never caller + * context. + */ +public final class AccountPlayerAdmissionEntitlementWorkloadGuard implements ServerInterceptor { + private final Context.Key authenticatedCaller = + Context.key("player-admission-game-session-peer"); + private final String expectedWorkload; + + public AccountPlayerAdmissionEntitlementWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + expectedWorkload = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + } + + /** Only this guard's TLS interception can supply the private method-authorized assertion. */ + public String requireAuthenticatedGameSessionCaller() { + if (!expectedWorkload.equals(authenticatedCaller.get()) || hasSessionContext()) { + throw Status.UNAUTHENTICATED + .withDescription("Protected Game Session workload call required") + .asRuntimeException(); + } + return expectedWorkload; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); + if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); + if (!expectedWorkload.equals(peer.orElseThrow().uri()) + || hasSessionContext() + || !AccountPlayerAdmissionEntitlementReadServiceGrpc + .getReadPlayerAdmissionEntitlementMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName())) { + return deny(call, Status.PERMISSION_DENIED); + } + return Contexts.interceptCall( + Context.current().withValue(authenticatedCaller, peer.orElseThrow().uri()), + call, + headers, + next); + } + + private static boolean hasSessionContext() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private static ServerCall.Listener deny( + ServerCall call, Status status) { + call.close( + status.withDescription("Exact protected Game Session entitlement method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java new file mode 100644 index 0000000000..7c46b60d73 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.accountservice.service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import java.time.Clock; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.Date; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered reader for an exact signed V2 public-production connect scope and its Account row. + * + *

The expected Account UUID is comparison data supplied by an outer authenticating owner; this + * reader does not authenticate a caller or create a caller context. It returns only the persisted + * V2 selector. Neither constructing nor reading the selector grants membership, JOIN, or gameplay + * authority. + */ +public final class AccountCanonicalConnectScopeReader { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUDIENCE = "bootstrap-connect-scope"; + private static final String INVALID_MESSAGE = "Canonical connect scope is invalid"; + private static final String UNAVAILABLE_MESSAGE = "Account authority is unavailable"; + + private final JwtUtil jwt; + private final AccountConnectScopeRepository scopes; + private final TransactionTemplate transaction; + private final Clock clock; + + public AccountCanonicalConnectScopeReader( + JwtUtil jwt, + AccountConnectScopeRepository scopes, + PlatformTransactionManager transactions, + Clock clock) { + this.jwt = Objects.requireNonNull(jwt, "JWT verifier is required"); + this.scopes = Objects.requireNonNull(scopes, "Account scope repository is required"); + this.clock = Objects.requireNonNull(clock, "Account clock is required"); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.setTimeout(5); + } + + /** Reads the persisted scope only when it exactly matches this signed bearer and Account UUID. */ + public CanonicalJoinScopeV2 read(UUID expectedAccountId, String presentedScope) { + requireNoAmbientTransaction(); + if (expectedAccountId == null || NIL_UUID.equals(expectedAccountId)) throw invalid(null); + + final CanonicalJoinScopeV2 signed; + try { + signed = verifySignedScope(expectedAccountId, presentedScope); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + String tokenHash = AccountJoinDigest.tokenHash(presentedScope); + final CanonicalJoinScopeV2 retained; + try { + retained = + Objects.requireNonNull( + transaction.execute(status -> readRetained(expectedAccountId, tokenHash, signed)), + "Account scope transaction returned no result"); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + + requireCurrentScopeTime(signed); + if (!signed.equals(retained)) throw invalid(null); + return retained; + } + + private CanonicalJoinScopeV2 verifySignedScope(UUID expectedAccountId, String token) { + if (token == null || token.isBlank() || !token.equals(token.trim())) throw invalid(null); + + final Claims claims; + try { + claims = jwt.parseToken(token).getPayload(); + } catch (JwtException | IllegalArgumentException failure) { + throw invalid(null); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + + try { + // JJWT normalizes the signed aud string to a set. Require this one exact audience rather + // than relying on a string cast or accepting the first value of a multi-audience token. + if (!Set.of(AUDIENCE).equals(claims.getAudience())) throw invalid(null); + String subject = JwtClaims.requireCanonicalAccountUuid(claims.getSubject(), "sub"); + String accountText = + JwtClaims.requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); + if (!subject.equals(accountText) || !expectedAccountId.toString().equals(accountText)) { + throw invalid(null); + } + requireNonNilUuid(claims.get("jti"), "jti"); + if (!"PUBLIC_PRODUCTION".equals(requireString(claims.get("targetClass"), "targetClass"))) { + throw invalid(null); + } + if (requireIntegralLong(claims.get("scopeDigestVersion"), "scopeDigestVersion") != 2L) { + throw invalid(null); + } + + UUID tenantId = requireNonNilUuid(claims.get("tenantId"), "tenantId"); + UUID realmId = requireNonNilUuid(claims.get("realmId"), "realmId"); + UUID namespaceId = + requireNonNilUuid(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"); + UUID gameInstanceId = requireNonNilUuid(claims.get("gameInstanceId"), "gameInstanceId"); + long catalogRevision = requireIntegralLong(claims.get("catalogRevision"), "catalogRevision"); + long pointerVersion = requireIntegralLong(claims.get("pointerVersion"), "pointerVersion"); + Instant evaluatedAt = requireCanonicalInstant(claims.get("evaluatedAt"), "evaluatedAt"); + Instant expiresAt = + requireCanonicalInstant(claims.get("connectScopeExpiresAt"), "connectScopeExpiresAt"); + Date issuedAt = claims.getIssuedAt(); + Date jwtExpiresAt = claims.getExpiration(); + if (issuedAt == null + || jwtExpiresAt == null + || !issuedAt.toInstant().isAfter(Instant.EPOCH) + || !issuedAt.toInstant().isBefore(jwtExpiresAt.toInstant()) + || !expiresAt.equals(jwtExpiresAt.toInstant()) + || !expiresAt.isAfter(evaluatedAt)) { + throw invalid(null); + } + + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + token, + expectedAccountId, + tenantId, + realmId, + requireString(claims.get("tenantSlug"), "tenantSlug"), + requireString(claims.get("worldSlug"), "worldSlug"), + requireString(claims.get("realmSlug"), "realmSlug"), + namespaceId, + requireString(claims.get("playableStateScope"), "playableStateScope"), + gameInstanceId, + catalogRevision, + pointerVersion, + evaluatedAt.toString(), + expiresAt.toString()); + requireCurrentScopeTime(scope); + return scope; + } catch (AuthenticationException failure) { + throw failure; + } catch (JwtException + | DateTimeException + | IllegalArgumentException + | ArithmeticException failure) { + throw invalid(failure); + } + } + + private CanonicalJoinScopeV2 readRetained( + UUID expectedAccountId, String tokenHash, CanonicalJoinScopeV2 signed) { + try { + CanonicalJoinScopeV2 retained = + scopes.findCanonical(signed.connectScopeId()).orElseThrow(() -> invalid(null)); + CanonicalConnectScopeEvidence evidence = + scopes.findCanonicalEvidenceByTokenHash(tokenHash).orElseThrow(() -> invalid(null)); + String digest = AccountJoinDigest.scopeV2(signed); + if (!expectedAccountId.equals(retained.accountId()) + || !signed.equals(retained) + || !tokenHash.equals(evidence.scopeTokenHash()) + || evidence.privateAccountId() <= 0L + || !"PUBLIC_PRODUCTION".equals(evidence.targetClass()) + || evidence.scopeDigestVersion() != 2 + || !digest.equals(evidence.scopeDigest()) + || evidence.tenantProvenance() == null + || !evidence.accountUuid().equals(signed.accountId()) + || !evidence.tenantUuid().equals(signed.tenantId()) + || !evidence.realmId().equals(signed.realmId()) + || !evidence.tenantSlug().equals(signed.tenantSlug()) + || !evidence.worldSlug().equals(signed.worldSlug()) + || !evidence.realmSlug().equals(signed.realmSlug()) + || !evidence.playableStateNamespaceUuid().equals(signed.playableStateNamespaceId()) + || !evidence.playableStateScope().equals(signed.playableStateScope()) + || !evidence.gameInstanceUuid().equals(signed.gameInstanceId()) + || evidence.catalogRevision() != signed.catalogRevision() + || evidence.pointerVersion() != signed.pointerVersion() + || !evidence.evaluatedAt().equals(signed.evaluatedAt()) + || !evidence.connectScopeExpiresAt().equals(signed.connectScopeExpiresAt())) { + throw invalid(null); + } + return retained; + } catch (AuthenticationException failure) { + throw failure; + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + throw failure; + } catch (RuntimeException failure) { + throw invalid(failure); + } + } + + private void requireCurrentScopeTime(CanonicalJoinScopeV2 scope) { + Instant now = clock.instant(); + Instant evaluatedAt = Instant.parse(scope.evaluatedAt()); + Instant expiresAt = Instant.parse(scope.connectScopeExpiresAt()); + if (now.isBefore(evaluatedAt) || !now.isBefore(expiresAt)) throw invalid(null); + } + + private static String requireString(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty() || !text.equals(text.trim())) { + throw new IllegalArgumentException("Malformed claim: " + field); + } + return text; + } + + private static UUID requireNonNilUuid(Object value, String field) { + String text = requireString(value, field); + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException("Malformed claim: " + field); + } + return parsed; + } + + private static long requireIntegralLong(Object value, String field) { + final long result; + if (value instanceof Integer integer) result = integer.longValue(); + else if (value instanceof Long longValue) result = longValue; + else if (value instanceof Short shortValue) result = shortValue.longValue(); + else if (value instanceof Byte byteValue) result = byteValue.longValue(); + else throw new IllegalArgumentException("Malformed numeric claim: " + field); + if (result <= 0L) throw new IllegalArgumentException("Invalid numeric claim: " + field); + return result; + } + + private static Instant requireCanonicalInstant(Object value, String field) { + String text = requireString(value, field); + Instant parsed = Instant.parse(text); + if (!parsed.toString().equals(text)) { + throw new IllegalArgumentException("Non-canonical instant claim: " + field); + } + return parsed; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical connect-scope read requires no ambient Account transaction"); + } + } + + private static AuthenticationException invalid(Throwable ignored) { + // Do not retain the bearer or parser diagnostics that may include attacker-controlled text. + return new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_MESSAGE); + } + + private static AuthenticationException unavailable(Throwable cause) { + return new AuthenticationException("AUTH_UNAVAILABLE", UNAVAILABLE_MESSAGE, cause); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index c8c9bb63df..8d04676614 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; @@ -21,6 +22,8 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; @@ -43,8 +46,9 @@ import tools.jackson.databind.json.JsonMapper; /** - * Composes the existing canonical JOIN operation, first membership, authority event/pair, and - * Account-local tenant audit receipt in one caller-owned transaction. + * Composes canonical JOIN membership, authority event/pair, and Account-local terminal receipts in + * one caller-owned transaction. The exact first-JOIN primitive remains separately guarded; the + * existing-membership entry point retains ACTIVE snapshots or restores INACTIVE membership. * *

This is an owner-local persistence primitive, not a caller authenticator, target-currentness * check, public JOIN entry point, cross-service commit gate, or Logging receiver receipt. @@ -97,6 +101,262 @@ public AccountCanonicalFirstJoinTerminalCoordinator( @Transactional(propagation = Propagation.MANDATORY) public CanonicalJoinTerminalProof commitCanonicalFirstJoin( CanonicalJoinScopeV2 scope, String requestId, String verifiedCallerBinding) { + return commitCanonicalFirstJoin(scope, requestId, verifiedCallerBinding, null, null, null); + } + + /** + * Owner-local paid first JOIN, using the actual fence prepared in an earlier source transaction + * and sealed SDK observation obtained outside SQL. The final paid reread, membership/roles, + * authority event/pair, audit and terminal receipt share this caller-owned transaction. + * Exceptions must escape that transaction so every staged write rolls back. This supplies neither + * caller authentication nor a World hold; default Spring composition and the explicit demo path + * are unchanged. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinTerminalProof commitPaidCanonicalFirstJoin( + CanonicalJoinScopeV2 scope, + String requestId, + String verifiedCallerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + Objects.requireNonNull(hosting, "Actual paid hosting source required"); + Objects.requireNonNull(fence, "Original paid read fence required"); + Objects.requireNonNull(observed, "Original sealed SDK result required"); + return commitCanonicalFirstJoin( + scope, requestId, verifiedCallerBinding, hosting, fence, observed); + } + + /** + * Applies the accepted existing-membership JOIN lifecycle without reusing the first-row writer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence commitCanonicalJoin( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + requireWritableOwnerTransaction(); + Account account = accountRepository.findByAccountUuid(scope.accountId()).orElseThrow(); + requireAccountIdentity(account, scope.accountId()); + joinOperationRepository.lockAccount(account.getId()); + CanonicalJoinOperationEvidence operation = + joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); + requireExactOperation(operation, account.getId(), scope, requestId, callerBinding); + AccountTenantMembership membership = + membershipRepository + .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) + .orElse(null); + if (membership == null) { + if (hosting == null) commitCanonicalFirstJoin(scope, requestId, callerBinding); + else commitPaidCanonicalFirstJoin(scope, requestId, callerBinding, hosting, fence, observed); + return joinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + } + if ("PENDING".equals(operation.status())) { + eventProducer.requireCurrentCanonicalJoinPolicy( + scope, + operation, + !"ACTIVE".equals(membership.getLifecycleState()), + hosting, + fence, + observed); + } + VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + scope.accountId(), + scope.tenantId(), + provenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + PairAuthority previous = + pairAuthorityRepository.readForUpdate(scope.accountId(), scope.tenantId()).orElseThrow(); + String outcome; + Checkpoint checkpoint; + if ("COMMITTED".equals(operation.status())) { + outcome = operation.outcome(); + checkpoint = + authorityOutboxRepository + .readCheckpoint(operation.terminalProof().eventStreamKey()) + .orElseThrow(); + } else if ("ACTIVE".equals(membership.getLifecycleState())) { + outcome = "ALREADY_ACTIVE"; + checkpoint = + authorityOutboxRepository + .readCheckpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId()) + .orElseThrow(); + } else if ("INACTIVE".equals(membership.getLifecycleState())) { + if (!Boolean.TRUE.equals(operation.allowPublicJoin())) { + throw new IllegalStateException("Restore requires current positive public JOIN policy"); + } + membership = + membershipRepository.restoreFreshMembershipForJoin( + scope.accountId(), scope.tenantId(), membership); + List restoredRoles = new java.util.ArrayList<>(roles.roles()); + if (!restoredRoles.contains("player")) restoredRoles.add("player"); + roles = + roleSnapshotRepository.replaceCanonical( + membership, + scope.accountId(), + scope.tenantId(), + provenance, + membership.getMembershipVersion(), + restoredRoles); + checkpoint = + eventProducer.publishCanonicalRestoredMembershipChange( + scope, requestId, callerBinding, previous, hosting, fence, observed); + outcome = "JOINED"; + } else { + throw new IllegalStateException("Membership lifecycle does not allow JOIN"); + } + FirstJoinEvidence current = readCurrentJoinEvidence(scope, membership, roles, checkpoint); + if ("PENDING".equals(operation.status()) + && "ALREADY_ACTIVE".equals(outcome) + && requestId.equals(current.event().requestId())) { + throw new IllegalStateException("Pending JOIN cannot adopt its precommitted transition"); + } + if ("JOINED".equals(outcome) && !requestId.equals(current.event().requestId())) { + throw new IllegalStateException("Transition JOIN event does not belong to this request"); + } + final CanonicalJoinTerminalProof proof; + if ("ALREADY_ACTIVE".equals(outcome)) { + proof = + new CanonicalJoinTerminalProof( + checkpoint.outboxStreamKey(), + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + null, + null, + null, + operation.entitlementVersion(), + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + } else { + String payload = + canonicalCurrentAuditPayload(scope, requestId, operation, current, checkpoint); + UUID auditId = auditEventIdFor(requestId); + AccountAuditEnvelope audit; + if ("PENDING".equals(operation.status())) { + AccountAuditEnvelope appended = + auditOutboxRepository.appendCanonicalTenant( + auditId, scope.tenantId().toString(), JOINED_EVENT_TYPE, payload); + audit = + auditOutboxRepository.findExactCanonicalTenantEnvelopeForUpdate(appended).orElseThrow(); + } else { + audit = auditOutboxRepository.findCanonicalTenantEnvelopeForUpdate(auditId).orElseThrow(); + } + requireExactAudit(audit, scope, auditId, payload, operation.terminalProof()); + proof = proof(operation, current, audit); + } + return joinOperationRepository.commitCanonicalJoin( + requestId, scope, callerBinding, outcome, proof); + } + + private FirstJoinEvidence readCurrentJoinEvidence( + CanonicalJoinScopeV2 scope, + AccountTenantMembership membership, + RoleSnapshot roles, + Checkpoint checkpoint) { + PairAuthority pair = + pairAuthorityRepository.readForUpdate(scope.accountId(), scope.tenantId()).orElseThrow(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId(); + if (!stream.equals(checkpoint.outboxStreamKey()) + || !pair.membershipExists() + || !scope.accountId().equals(pair.accountUuid()) + || !scope.tenantId().equals(pair.tenantUuid()) + || pair.membershipVersion() != membership.getMembershipVersion() + || pair.membershipAuthorityGeneration() != membership.getMembershipAuthorityGeneration() + || pair.eventSequence() != checkpoint.outboxSequence() + || !pair.eventId().equals(checkpoint.sourceEventId()) + || !pair.eventDigest().equals(checkpoint.sourceEventDigest()) + || roles.snapshotVersion() != membership.getMembershipVersion() + || roles.membershipId() != membership.getId() + || !scope.accountId().equals(roles.accountUuid()) + || !scope.tenantId().equals(roles.tenantUuid()) + || !pair.provenance().equals(roles.tenantProvenance()) + || !"ACTIVE".equals(membership.getLifecycleState())) { + throw new IllegalStateException("Canonical JOIN current membership/pair/roles differ"); + } + Event event = + authorityOutboxRepository.findEvent(stream, checkpoint.outboxSequence()).orElseThrow(); + MembershipEvent decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(event.payload(), decoded.canonicalJsonUtf8()) + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest()) + || !event.eventId().equals(decoded.eventId()) + || !event.eventDigest().equals(decoded.eventDigest()) + || !scope.accountId().toString().equals(decoded.accountId()) + || !scope.tenantId().toString().equals(decoded.tenantId()) + || !Map.of(scope.tenantId().toString(), Long.toString(membership.getMembershipVersion())) + .equals(decoded.membershipVersion()) + || !Long.toString(membership.getMembershipAuthorityGeneration()) + .equals(decoded.membershipAuthorityGeneration()) + || !roles.roles().equals(decoded.roles()) + || !"ACTIVE".equals(decoded.membershipLifecycleState()) + || decoded.gameplayAdmissionAllowed() != membership.isGameplayAdmissionAllowed()) { + throw new IllegalStateException("Canonical JOIN current event contradicts owner snapshot"); + } + return new FirstJoinEvidence(membership, event); + } + + private static String canonicalCurrentAuditPayload( + CanonicalJoinScopeV2 scope, + String requestId, + CanonicalJoinOperationEvidence operation, + FirstJoinEvidence current, + Checkpoint checkpoint) { + Map payload = new LinkedHashMap<>(); + payload.put("accountId", scope.accountId().toString()); + payload.put("tenantId", scope.tenantId().toString()); + payload.put("requestId", requestId); + payload.put("worldSlug", scope.worldSlug()); + payload.put("realmSlug", scope.realmSlug()); + payload.put("membershipVersion", current.membership().getMembershipVersion()); + payload.put( + "membershipAuthorityGeneration", current.membership().getMembershipAuthorityGeneration()); + payload.put("membershipEventStreamKey", checkpoint.outboxStreamKey()); + payload.put("membershipEventSequence", checkpoint.outboxSequence()); + payload.put("membershipEventId", checkpoint.sourceEventId()); + payload.put("membershipEventDigest", checkpoint.sourceEventDigest()); + payload.put("joinIntentDigest", operation.intentDigest()); + payload.put("joinRequestDigest", operation.requestDigest()); + payload.put("allowPublicJoin", true); + payload.put("entitlementVersion", operation.entitlementVersion()); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(payload)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalStateException("Canonical JOIN audit cannot be encoded", failure); + } + } + + private CanonicalJoinTerminalProof commitCanonicalFirstJoin( + CanonicalJoinScopeV2 scope, + String requestId, + String verifiedCallerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { requireWritableOwnerTransaction(); Objects.requireNonNull(scope, "canonical JOIN scope is required"); requireBoundedText(requestId, "canonical JOIN request ID"); @@ -117,6 +377,10 @@ public CanonicalJoinTerminalProof commitCanonicalFirstJoin( () -> new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts")); requireExactOperation(operation, account.getId(), scope, requestId, verifiedCallerBinding); + if (!Boolean.TRUE.equals(operation.allowPublicJoin())) { + throw new CanonicalJoinOperationConflictException( + "First JOIN requires available public policy"); + } final Checkpoint checkpoint; if ("PENDING".equals(operation.status())) { @@ -139,8 +403,11 @@ public CanonicalJoinTerminalProof commitCanonicalFirstJoin( requireExactRoleSnapshot(staged, provenance, scope, stagedRoles); checkpoint = - eventProducer.publishCanonicalFirstJoinMembershipChange( - scope, requestId, verifiedCallerBinding); + hosting == null + ? eventProducer.publishCanonicalFirstJoinMembershipChange( + scope, requestId, verifiedCallerBinding) + : eventProducer.publishPaidCanonicalFirstJoinMembershipChange( + scope, requestId, verifiedCallerBinding, hosting, fence, observed); } else if ("COMMITTED".equals(operation.status()) && "JOINED".equals(operation.outcome()) && operation.terminalProof() != null) { @@ -332,7 +599,7 @@ private static void requireExactOperation( throw new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts"); } if (!"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) - || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.allowPublicJoin() == null || operation.entitlementVersion() == null || operation.entitlementVersion() <= 0L || !Integer.valueOf(2).equals(operation.requestDigestVersion()) @@ -346,7 +613,7 @@ private static void requireExactOperation( scope, callerBinding, AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, - true, + operation.allowPublicJoin(), operation.entitlementVersion()); if (!requestDigest.equals(operation.requestDigest())) { throw new CanonicalJoinOperationConflictException("Canonical JOIN policy conflicts"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index f6214b95f1..3c8e3ef82a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -16,6 +16,8 @@ import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -51,7 +53,10 @@ * current identity, provenance, membership and billing heads; the final transaction retains and * exactly reads back the V2 scope. Every repository must use the supplied transaction manager. * - *

Membership-independent public visibility is preserved when enrollment is closed. Returned + *

Browser credentials use their persisted Account/session-registry verifier. Direct text uses + * the exact same-namespace Game Session peer and canonical caller correlation, with its own + * invocation deadline; it never fabricates a bootstrap credential or registry success. + * Membership-independent public visibility is preserved when enrollment is closed. Returned * membership/entitlement facts are observations for later selection, never permission to JOIN, * create a character or admit gameplay. This owner neither enrolls membership nor claims a World * hold, private/ISOLATED support, a registered facade, or qualified credential custody. @@ -112,35 +117,149 @@ public AccountCanonicalPublicRealmScopeOwner( transaction.setReadOnly(false); } - /** Selects only the canonical tenant/world pair; a bare global world slug is not authority. */ + /** Resolves a world only when the complete public collection identifies one exact target. */ + public List listRealmScopes(String bootstrapToken, String worldSlug) { + return listRealmScopes(bootstrapToken, null, worldSlug, false); + } + + /** Selects the canonical tenant/world pair through the same complete-source pipeline. */ public List listRealmScopes( String bootstrapToken, String tenantSlug, String worldSlug) { + return listRealmScopes(bootstrapToken, tenantSlug, worldSlug, true); + } + + private List listRealmScopes( + String bootstrapToken, String tenantSlug, String worldSlug, boolean tenantQualified) { requireSourceContext(); Caller original = verifyCaller(bootstrapToken); - if (!RealmEntryPolicy.isCanonicalSlug(tenantSlug) + return listRealmScopes( + original, tenantSlug, worldSlug, tenantQualified, () -> verifyCaller(bootstrapToken), null); + } + + /** Existing direct-text selection, authenticated independently of the browser registry. */ + public RealmScope issueDirectTextScope( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + requireSourceContext(); + requireDirectPeer(); + if (caller == null + || target == null + || !Objects.equals(caller.tenantId(), target.tenantId()) + || !Objects.equals(caller.realmId(), target.realmId()) + || !Objects.equals(caller.playableStateNamespaceId(), target.playableStateNamespaceId()) + || !Objects.equals(caller.gameInstanceId(), target.gameInstanceId()) + || !Objects.equals(caller.playableStateScope(), target.playableStateScope()) + || caller.sessionId() == null + || caller.requestId() == null + || caller.sessionId().isBlank() + || caller.requestId().isBlank() + || caller.sessionId().length() > 128 + || caller.requestId().length() > 128) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller correlation is invalid"); + } + try { + UUID session = UUID.fromString(caller.sessionId()); + if (!session.toString().equals(caller.sessionId()) || new UUID(0L, 0L).equals(session)) { + throw new IllegalArgumentException("Invalid session correlation"); + } + } catch (IllegalArgumentException failure) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller session is invalid"); + } + // These times describe this Account producer invocation, not a fabricated bootstrap lifetime. + Instant issuedAt = now(); + Instant deadline = issuedAt.plusMillis(scopeLifetimeMillis); + java.util.function.Supplier authenticate = + () -> verifyDirectCaller(caller, issuedAt, deadline); + Caller original = authenticate.get(); + List selected = + listRealmScopes(original, null, target.worldSlug(), false, authenticate, target); + if (selected.size() != 1) throw pointerUnavailable(null); + return selected.getFirst(); + } + + private Caller verifyDirectCaller( + DirectTextCallerContext context, Instant issuedAt, Instant deadline) { + requireDirectPeer(); + if (context.accountId() == null + || new UUID(0L, 0L).equals(context.accountId()) + || now().isBefore(issuedAt) + || !now().isBefore(deadline)) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller expired or malformed"); + } + return inTransaction( + () -> { + requireDirectPeer(); + Account account = accounts.findByAccountUuidForUpdate(context.accountId()).orElseThrow(); + if (account.getId() == null + || account.getId() <= 0L + || !context.accountId().equals(account.getAccountUuid()) + || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { + throw authUnavailable("Direct Account owner is unavailable or ineligible", null); + } + return new Caller(account.getId(), account.getAccountUuid(), issuedAt, deadline); + }); + } + + private void requireDirectPeer() { + var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.current(); + if (peer == null || !peer.isService("game-session-service") || !peer.isInNamespace(namespace)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Exact Game Session workload is required"); + } + } + + private List listRealmScopes( + Caller original, + String tenantSlug, + String worldSlug, + boolean tenantQualified, + java.util.function.Supplier authenticate, + DirectTextJoinTarget directTarget) { + if ((tenantQualified && !RealmEntryPolicy.isCanonicalSlug(tenantSlug)) || !RealmEntryPolicy.isCanonicalSlug(worldSlug)) { throw pointerUnavailable(null); } - Optional selected = select(readTargets(), tenantSlug, worldSlug); + Optional selected = + selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget); if (selected.isEmpty()) { - if (select(readTargets(), tenantSlug, worldSlug).isPresent()) { + if (selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget) + .isPresent()) { throw pointerUnavailable(null); } - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameCaller(original, authenticate.get()); return List.of(); } Target target = selected.orElseThrow(); + if (directTarget != null + && (!directTarget.tenantId().equals(target.canonicalTenantId()) + || !directTarget.realmId().equals(target.realmId()) + || !directTarget.realmSlug().equals(target.realmSlug()) + || !directTarget.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !directTarget.playableStateScope().equals(target.playableStateScope()) + || !directTarget.gameInstanceId().equals(target.canonicalGameInstanceId()) + || directTarget.catalogRevision() != target.catalogRevision() + || directTarget.pointerVersion() != target.pointerVersion())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", "Direct target changed"); + } Evaluation entitlement = evaluate(target); if (!entitlement.gameplayAvailable()) { - requireSameTarget(target, select(readTargets(), tenantSlug, worldSlug)); - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameTarget( + target, + selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget)); + requireSameCaller(original, authenticate.get()); requireFresh(entitlement); return List.of(); } Prepared prepared = inTransaction(() -> readSources(original, target, entitlement)); - requireSameTarget(target, select(readTargets(), tenantSlug, worldSlug)); - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameTarget( + target, + selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget)); + requireSameCaller(original, authenticate.get()); requireFresh(entitlement); RealmScope retained = inTransaction( @@ -172,7 +291,7 @@ public List listRealmScopes( TenantProvenanceKind.FRESH_GAME_DESIGN, current.tenant().operationId(), current.tenant().evidenceDigest()); - scopes.insertCanonical(original.caller().accountId(), scope, provenance); + scopes.insertCanonical(original.accountId(), scope, provenance); if (!scope.equals(scopes.findCanonical(scope.connectScopeId()).orElse(null))) { throw authUnavailable("Canonical scope readback differs", null); } @@ -186,7 +305,7 @@ public List listRealmScopes( return new RealmScope(target, scope, current.membership(), entitlement); }); // No value escapes a failed commit or a caller/source observation that expired during commit. - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameCaller(original, authenticate.get()); requireFresh(entitlement); if (!now().isBefore(Instant.parse(retained.scope().connectScopeExpiresAt()))) { throw authUnavailable("Canonical scope expired before publication", null); @@ -217,7 +336,7 @@ private Caller verifyCaller(String token) { throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "Invalid bootstrap credential"); } - return new Caller(caller, issuedAt, expiresAt); + return new Caller(caller.accountId(), caller.accountUuid(), issuedAt, expiresAt); } catch (AuthenticationException failure) { throw failure; } catch (JwtException | IllegalArgumentException failure) { @@ -247,12 +366,14 @@ private List readTargets() { } } - private Optional select(List complete, String tenantSlug, String worldSlug) { + private Optional select( + List complete, String tenantSlug, String worldSlug, boolean tenantQualified) { List matches = complete.stream() .filter( target -> - tenantSlug.equals(target.tenantSlug()) && worldSlug.equals(target.worldSlug())) + worldSlug.equals(target.worldSlug()) + && (!tenantQualified || tenantSlug.equals(target.tenantSlug()))) .toList(); if (matches.size() > 1) throw pointerUnavailable(null); for (Target target : matches) { @@ -265,6 +386,21 @@ private Optional select(List complete, String tenantSlug, String return matches.stream().findFirst(); } + private Optional selectForCaller( + List complete, + String tenantSlug, + String worldSlug, + boolean tenantQualified, + DirectTextJoinTarget directTarget) { + List selectedTenant = + directTarget == null + ? complete + : complete.stream() + .filter(target -> directTarget.tenantId().equals(target.canonicalTenantId())) + .toList(); + return select(selectedTenant, tenantSlug, worldSlug, tenantQualified); + } + private Evaluation evaluate(Target target) { requireSourceContext(); try { @@ -286,10 +422,10 @@ private Evaluation evaluate(Target target) { private Prepared readSources(Caller caller, Target target, Evaluation entitlement) { Account account = accounts - .findByAccountUuidForUpdate(caller.caller().accountUuid()) + .findByAccountUuidForUpdate(caller.accountUuid()) .orElseThrow(() -> authUnavailable("Account owner is unavailable", null)); - if (!Objects.equals(account.getId(), caller.caller().accountId()) - || !caller.caller().accountUuid().equals(account.getAccountUuid()) + if (!Objects.equals(account.getId(), caller.accountId()) + || !caller.accountUuid().equals(account.getAccountUuid()) || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { @@ -317,8 +453,7 @@ private Prepared readSources(Caller caller, Target target, Evaluation entitlemen throw entitlementUnavailable(failure); } Optional member = - memberships.findFreshMembershipForUpdate( - caller.caller().accountUuid(), target.canonicalTenantId()); + memberships.findFreshMembershipForUpdate(caller.accountUuid(), target.canonicalTenantId()); Optional current = member.map( value -> { @@ -356,7 +491,7 @@ private CanonicalJoinScopeV2 mintScope( Caller caller, Target target, Instant evaluatedAt, Instant expiresAt) { Map claims = new LinkedHashMap<>(); claims.put("aud", "bootstrap-connect-scope"); - claims.put("accountId", caller.caller().accountUuid().toString()); + claims.put("accountId", caller.accountUuid().toString()); claims.put("targetClass", "PUBLIC_PRODUCTION"); claims.put("scopeDigestVersion", 2L); claims.put("tenantId", target.canonicalTenantId().toString()); @@ -375,12 +510,12 @@ private CanonicalJoinScopeV2 mintScope( // Preserve the owner-selected absolute expiry even if signing starts after a scheduling pause. final String token; try { - token = jwt.generateToken(caller.caller().accountUuid().toString(), expiresAt, claims); + token = jwt.generateToken(caller.accountUuid().toString(), expiresAt, claims); } catch (IllegalArgumentException expired) { throw authUnavailable("Scope signing clock is outside its validity", null); } Claims signed = jwt.parseToken(token).getPayload(); - if (!caller.caller().accountUuid().toString().equals(signed.getSubject()) + if (!caller.accountUuid().toString().equals(signed.getSubject()) || signed.getExpiration() == null || !expiresAt.equals(signed.getExpiration().toInstant()) || signed.getIssuedAt() == null @@ -401,7 +536,7 @@ private CanonicalJoinScopeV2 mintScope( } return new CanonicalJoinScopeV2( token, - caller.caller().accountUuid(), + caller.accountUuid(), target.canonicalTenantId(), target.realmId(), target.tenantSlug(), @@ -420,7 +555,7 @@ private static CanonicalConnectScopeEvidence evidence( Caller caller, CanonicalJoinScopeV2 scope, VerifiedTenantProvenance provenance) { return new CanonicalConnectScopeEvidence( AccountJoinDigest.tokenHash(scope.connectScopeId()), - caller.caller().accountId(), + caller.accountId(), "PUBLIC_PRODUCTION", scope.accountId(), scope.tenantId(), @@ -470,8 +605,8 @@ private void requireFresh(Evaluation evaluation) { } private static void requireSameCaller(Caller original, Caller current) { - if (original.caller().accountId() != current.caller().accountId() - || !original.caller().accountUuid().equals(current.caller().accountUuid()) + if (original.accountId() != current.accountId() + || !original.accountUuid().equals(current.accountUuid()) || !original.issuedAt().equals(current.issuedAt()) || !original.expiresAt().equals(current.expiresAt())) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap caller changed"); @@ -519,7 +654,7 @@ private static AuthenticationException entitlementUnavailable(Throwable cause) { cause); } - private record Caller(VerifiedCaller caller, Instant issuedAt, Instant expiresAt) {} + private record Caller(long accountId, UUID accountUuid, Instant issuedAt, Instant expiresAt) {} private record Prepared( FreshTenantCreationEvidence tenant, MembershipFacts membership, SourceSelection head) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index ab72901bfb..90b1d52d81 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -11,6 +11,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; @@ -28,6 +29,9 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -117,6 +121,219 @@ public AccountMembershipAuthorityEventProducer( @Transactional(propagation = Propagation.MANDATORY) public Checkpoint publishCanonicalFirstJoinMembershipChange( CanonicalJoinScopeV2 scope, String requestId, String callerBinding) { + return publishCanonicalFirstJoinMembershipChange(scope, requestId, callerBinding, null); + } + + /** + * Separate manually composed paid source. The fence and sealed SDK Result must have been prepared + * outside this final transaction; this method performs only the actual locked receipt reread. No + * parsed runtime bundle or billing-owner identity supplies player authority. A COMMITTED exact + * replay follows the unchanged historical event/pair path without provider work. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishPaidCanonicalFirstJoinMembershipChange( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + return publishCanonicalFirstJoinMembershipChange( + scope, requestId, callerBinding, new PaidJoinSource(hosting, fence, observed)); + } + + /** Publishes exactly the next event for a staged INACTIVE restore under its prior pair fence. */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishCanonicalRestoredMembershipChange( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + PairAuthority previous, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(previous); + var account = accountRepository.findByAccountUuid(scope.accountId()).orElseThrow(); + joinOperationRepository.lockAccount(account.getId()); + CanonicalJoinOperationEvidence operation = + joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); + requireOperationMatchesRequest(scope, requestId, callerBinding, account.getId(), operation); + if (!"PENDING".equals(operation.status()) + || !previous.membershipExists() + || previous.eventSequence() <= 0L + || !previous.equals( + pairAuthorityRepository + .readForUpdate(scope.accountId(), scope.tenantId()) + .orElseThrow())) { + throw new IllegalStateException("Restore event requires its exact positive predecessor"); + } + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(scope.accountId(), scope.tenantId()) + .orElseThrow(); + VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); + requireExactPairScope(previous, scope.accountId(), scope.tenantId(), provenance); + if (!Objects.equals(account.getId(), membership.getAccount().getId()) + || !scope.accountId().equals(membership.getAccount().getAccountUuid()) + || !scope.tenantId().equals(membership.getTenantUuid()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance()) + || membership.getMembershipVersion() != Math.incrementExact(previous.membershipVersion()) + || membership.getMembershipAuthorityGeneration() + != previous.membershipAuthorityGeneration()) { + throw new IllegalStateException("Restore event contradicts its staged membership"); + } + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + scope.accountId(), + scope.tenantId(), + provenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + if (roles.snapshotVersion() != membership.getMembershipVersion() + || !roles.roles().contains("player")) { + throw new IllegalStateException("Restore event requires exact current player roles"); + } + CompositeSnapshot authority = + authorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, + scope.accountId(), + List.of(scope.tenantId()), + List.of(scope.tenantId())); + IssuerAccountSourceSnapshot sources = + sourceEvidenceRepository.readCurrentIssuerAccountSources( + ACCOUNT_JWT_ISSUER, scope.accountId()); + var tenant = + readCurrentTenantSourceEvent( + scope.tenantId(), provenance, only(authority.tenants(), "tenant")); + requireCurrentAuthority( + authority, + sources, + account.getId(), + scope.accountId(), + scope.tenantId(), + membership, + provenance, + tenant); + if (hosting == null) { + requireCurrentJoinEntitlement( + operation, + demoTenantEntitlementRepository.readCurrent(scope.tenantId()), + tenant, + scope.tenantId()); + } else { + requireCurrentPaidJoinEntitlement( + operation, hosting.readCurrent(fence, observed), tenant, scope.tenantId()); + } + String stream = membershipStreamKey(scope.accountId(), scope.tenantId()); + Checkpoint prior = authorityOutboxRepository.readCheckpoint(stream).orElseThrow(); + if (prior.outboxSequence() != previous.eventSequence() + || !prior.sourceEventId().equals(previous.eventId()) + || !prior.sourceEventDigest().equals(previous.eventDigest())) { + throw new IllegalStateException("Restore event predecessor differs from current event head"); + } + Event priorEvent = + authorityOutboxRepository.findEvent(stream, previous.eventSequence()).orElseThrow(); + MembershipEvent priorMembership = + MembershipAuthorityEventV1Codec.verify( + new String(priorEvent.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(priorMembership.canonicalJsonUtf8(), priorEvent.payload()) + || !previous.eventId().equals(priorEvent.eventId()) + || !previous.eventDigest().equals(priorEvent.eventDigest()) + || !previous.eventId().equals(priorMembership.eventId()) + || !previous.eventDigest().equals(priorMembership.eventDigest()) + || !scope.accountId().toString().equals(priorMembership.accountId()) + || !scope.tenantId().toString().equals(priorMembership.tenantId()) + || !"INACTIVE".equals(priorMembership.membershipLifecycleState()) + || priorMembership.gameplayAdmissionAllowed() + || !Map.of(scope.tenantId().toString(), Long.toString(previous.membershipVersion())) + .equals(priorMembership.membershipVersion()) + || !Long.toString(previous.membershipAuthorityGeneration()) + .equals(priorMembership.membershipAuthorityGeneration())) { + throw new IllegalStateException("Restore requires the exact published INACTIVE predecessor"); + } + long next = Math.incrementExact(previous.eventSequence()); + Event appended = + authorityOutboxRepository.append( + stream, + requestId, + sequence -> { + if (sequence != next) + throw new IllegalStateException("Restore event sequence changed"); + MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + scope, + membership, + roles.roles(), + authority, + sources, + tenant, + eventIdForRequest(requestId), + requestId, + sequence)); + return new EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + Event readback = authorityOutboxRepository.findEvent(stream, next).orElseThrow(); + if (!appended.equals(readback) || !requestId.equals(readback.requestId())) { + throw new IllegalStateException("Restore event readback differs"); + } + MembershipEvent decoded = + MembershipAuthorityEventV1Codec.verify( + new String(readback.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(decoded.canonicalJsonUtf8(), readback.payload()) + || !decoded.eventDigest().equals(readback.eventDigest())) { + throw new IllegalStateException("Restore event bytes differ from canonical digest"); + } + Checkpoint checkpoint = authorityOutboxRepository.readCheckpoint(stream).orElseThrow(); + requireCheckpointMatchesEvent(checkpoint, readback); + pairAuthorityRepository.commitRestore( + previous, + new PairTransition(true, next, readback.eventId(), readback.eventDigest(), false)); + return checkpoint; + } + + /** Rechecks actual Account policy sources under the caller's final membership transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public void requireCurrentCanonicalJoinPolicy( + CanonicalJoinScopeV2 scope, + CanonicalJoinOperationEvidence expected, + boolean transition, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + requireWritableOwnerTransaction(); + var current = + joinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(expected.requestId()) + .orElseThrow(); + if (!current.equals(expected) + || !AccountJoinDigest.scopeV2(scope).equals(current.connectScopeDigest()) + || !scope.accountId().equals(current.scopeEvidence().accountUuid()) + || !scope.tenantId().equals(current.scopeEvidence().tenantUuid())) { + throw new IllegalStateException("Canonical JOIN policy selector changed"); + } + var tenant = tenantAuthorityEventRepository.readCurrentByTenant(scope.tenantId()); + if (hosting == null) { + requireCurrentJoinEntitlement( + current, + demoTenantEntitlementRepository.readCurrent(scope.tenantId()), + tenant, + scope.tenantId(), + transition); + } else { + requireCurrentPaidJoinEntitlement( + current, hosting.readCurrent(fence, observed), tenant, scope.tenantId(), transition); + } + } + + private Checkpoint publishCanonicalFirstJoinMembershipChange( + CanonicalJoinScopeV2 scope, String requestId, String callerBinding, PaidJoinSource paid) { requireWritableOwnerTransaction(); Objects.requireNonNull(scope, "canonical JOIN scope is required"); requireBoundedText(requestId, "canonical JOIN request ID", MAX_REQUEST_ID_LENGTH); @@ -204,9 +421,16 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( membership, provenance, tenantSourceEvent); - DemoTenantEntitlementSnapshot entitlementSnapshot = - demoTenantEntitlementRepository.readCurrent(tenantUuid); - requireCurrentJoinEntitlement(operation, entitlementSnapshot, tenantSourceEvent, tenantUuid); + if (paid == null) { + DemoTenantEntitlementSnapshot entitlementSnapshot = + demoTenantEntitlementRepository.readCurrent(tenantUuid); + requireCurrentJoinEntitlement( + operation, entitlementSnapshot, tenantSourceEvent, tenantUuid); + } else { + AccountHostingSubscriptionCurrentReceipt receipt = + paid.hosting().readCurrent(paid.fence(), paid.observed()); + requireCurrentPaidJoinEntitlement(operation, receipt, tenantSourceEvent, tenantUuid); + } if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { throw new IllegalStateException( "Canonical first JOIN cannot publish over retained membership-event history"); @@ -543,10 +767,20 @@ private static void requireCurrentJoinEntitlement( DemoTenantEntitlementSnapshot entitlement, TenantAuthorityEventV1Codec.Event tenantSourceEvent, UUID tenantUuid) { + requireCurrentJoinEntitlement(operation, entitlement, tenantSourceEvent, tenantUuid, true); + } + + private static void requireCurrentJoinEntitlement( + CanonicalJoinOperationEvidence operation, + DemoTenantEntitlementSnapshot entitlement, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, + UUID tenantUuid, + boolean transition) { if (entitlement == null || !tenantUuid.equals(entitlement.canonicalTenantId()) || entitlement.entitlementVersion() != operation.entitlementVersion() - || !entitlement.allowPublicJoin() + || (transition && !entitlement.allowPublicJoin()) + || !Objects.equals(entitlement.allowPublicJoin(), operation.allowPublicJoin()) || !entitlement.gameplayAvailable() || tenantSourceEvent == null || !tenantUuid.equals(tenantSourceEvent.tenantId()) @@ -567,6 +801,62 @@ private static void requireCurrentJoinEntitlement( } } + private static void requireCurrentPaidJoinEntitlement( + CanonicalJoinOperationEvidence operation, + AccountHostingSubscriptionCurrentReceipt receipt, + TenantAuthorityEventV1Codec.Event currentTenant, + UUID tenantUuid) { + requireCurrentPaidJoinEntitlement(operation, receipt, currentTenant, tenantUuid, true); + } + + private static void requireCurrentPaidJoinEntitlement( + CanonicalJoinOperationEvidence operation, + AccountHostingSubscriptionCurrentReceipt receipt, + TenantAuthorityEventV1Codec.Event currentTenant, + UUID tenantUuid, + boolean transition) { + if (receipt == null + || receipt.current() == null + || currentTenant == null + || !tenantUuid.equals(receipt.current().tenantId()) + || receipt.entitlementVersion() != operation.entitlementVersion() + || (transition && !receipt.allowPublicJoin()) + || !Objects.equals(receipt.allowPublicJoin(), operation.allowPublicJoin()) + || !receipt.gameplayAvailable() + || receipt.evaluatedAt() == null + || receipt.validUntil() == null + || !receipt.evaluatedAt().isBefore(receipt.validUntil()) + || receipt.tenantAuthorityEvent() == null + || !Arrays.equals(receipt.tenantAuthorityEvent().payload(), currentTenant.payload()) + || !Objects.equals(receipt.tenantAuthorityEvent().eventId(), currentTenant.eventId()) + || !Objects.equals( + receipt.tenantAuthorityEvent().eventDigest(), currentTenant.eventDigest()) + || receipt.tenantAuthorityEvent().tenantAuthorityGeneration() + != currentTenant.tenantAuthorityGeneration() + || receipt.tenantAuthorityEvent().tenantAuthoritySourceVersion() + != currentTenant.tenantAuthoritySourceVersion() + || receipt.tenantAuthorityEvent().outboxSequence() != currentTenant.outboxSequence() + || !tenantUuid.equals(currentTenant.tenantId()) + || receipt.tenantBillingSequence() != currentTenant.tenantBillingSequence() + || !Objects.equals(receipt.billingEventId(), currentTenant.tenantBillingEventId()) + || !Objects.equals( + receipt.billingEventDigest(), currentTenant.tenantBillingEventDigest())) { + throw new IllegalStateException( + "Canonical paid first JOIN requires exact current public-join entitlement evidence"); + } + } + + private record PaidJoinSource( + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + private PaidJoinSource { + Objects.requireNonNull(hosting, "Actual paid hosting source required"); + Objects.requireNonNull(fence, "Original paid read fence required"); + Objects.requireNonNull(observed, "Original sealed SDK result required"); + } + } + private static List requireFirstJoinRoleSnapshot( CanonicalJoinScopeV2 scope, AccountTenantMembership membership, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java new file mode 100644 index 0000000000..fc705d2d1b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -0,0 +1,623 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account owner for PUBLIC_PRODUCTION SHARED PRESEEDED player entitlement evidence. + * JWT/registry, Stripe and protected Game Session/World reads run outside SQL. A final + * Account-first writable SERIALIZABLE transaction rereads caller issuance, membership (including + * explicit absence), exact persisted scope and paid/demo currentness before constructing the + * canonical value. No value escapes a failed commit. All repositories and the DSL must share the + * transaction manager. + * + *

The protected target is a point-in-time source read, not a World lock through this transaction + * or later mutation. This grants no capacity or admission. Request workload remains a trusted + * method-authorized transport assertion; parsing it does not authenticate it. No bean, public RPC, + * issuer or activation is supplied. Private/playtest and PLAYER_CREATED are unsupported. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected collaborators are private Account owner-source components.") +public final class AccountPlayerAdmissionEntitlementOwner { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountGameplayAdmissionCallerVerifier callers; + private final AccountGameplayDelegationIssuanceRepository issuances; + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; + private final AccountConnectScopeRepository scopes; + private final AccountHostingSubscriptionLifecycleRepository hosting; + private final StripeHostingSubscriptionObserver observer; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountTenantAuthorityEventRepository sources; + private final CanonicalGameplayAdmissionDecisionReadClient targets; + private final String namespace; + private final TransactionTemplate transaction; + private final Clock clock; + private final String expectedWorkload; + + public AccountPlayerAdmissionEntitlementOwner( + DSLContext dsl, + AccountRepository accounts, + AccountGameplayAdmissionCallerVerifier callers, + AccountGameplayDelegationIssuanceRepository issuances, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountConnectScopeRepository scopes, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + AccountDemoTenantEntitlementRepository demos, + AccountTenantAuthorityEventRepository sources, + CanonicalGameplayAdmissionDecisionReadClient targets, + PlatformTransactionManager transactions, + Clock clock, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.callers = Objects.requireNonNull(callers); + this.issuances = Objects.requireNonNull(issuances); + this.memberships = Objects.requireNonNull(memberships); + this.scopes = Objects.requireNonNull(scopes); + this.hosting = Objects.requireNonNull(hosting); + this.observer = Objects.requireNonNull(observer); + this.demos = Objects.requireNonNull(demos); + this.sources = Objects.requireNonNull(sources); + this.targets = Objects.requireNonNull(targets); + this.namespace = workloadNamespace; + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace is required"); + } + expectedWorkload = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + /** Selects the sole current Account-owned billing source; callers cannot select a family. */ + public RuntimePlayerAdmissionEntitlementEvidence evaluate( + Request request, String presentedInitialLoginJwt) { + VerifiedCaller caller = verifyCaller(request, presentedInitialLoginJwt); + Prepared prepared = + inSourceTransaction( + () -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + return new Prepared(player, sources.readCurrentSourceSelection(request.tenantId())); + }); + requireCurrentTimes(prepared.player(), now()); + RuntimePlayerAdmissionEntitlementEvidence evidence = + switch (prepared.selection().kind()) { + case PAID_HOSTING -> capturePaidSources(request, caller, prepared); + case NON_PAID_DEMO -> captureDemoSources(request, caller, prepared); + }; + evidence.requireCurrentAt(now()); + return evidence; + } + + private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( + Request request, VerifiedCaller caller, Prepared prepared) { + var fence = inSourceTransaction(() -> hosting.prepareCurrentRead(request.tenantId())); + requireNoAmbientTransaction(); + var observation = observer.observe(fence.binding()); + PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); + return inSourceTransaction( + () -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); + var receipt = hosting.readCurrent(fence, observation); + Instant evaluatedAt = now(); + requireFreshReceipt(request, receipt, evaluatedAt); + var event = receipt.tenantAuthorityEvent(); + if (!prepared.selection().matches(event)) throw unavailable(); + requireTenantSource( + player.snapshot(), + event.tenantId(), + event.tenantAuthorityGeneration(), + receipt.tenantBillingSequence(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + if (!receipt.billingEventId().equals(event.tenantBillingEventId()) + || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest()) + || receipt.tenantBillingSequence() != event.tenantBillingSequence()) { + throw unavailable(); + } + requireCurrentTimes(player, evaluatedAt); + var quote = receipt.current().planQuote(); + return capture( + request, + player, + target, + facts( + "PAID_HOSTING", + receipt.subscriptionStatus().storageValue(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes(), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + event.tenantAuthorityGeneration()), + RuntimePlayerAdmissionEntitlementEvidence.digest( + Map.of( + "receiptRequestId", receipt.receiptRequestId().toString(), + "subscriptionId", receipt.current().subscriptionId().toString(), + "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), + "billingEventId", receipt.billingEventId().toString(), + "billingEventDigest", receipt.billingEventDigest(), + "tenantAuthorityEventDigest", event.eventDigest())), + evaluatedAt, + receipt.validUntil()); + }); + } + + private RuntimePlayerAdmissionEntitlementEvidence captureDemoSources( + Request request, VerifiedCaller caller, Prepared prepared) { + PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); + return inSourceTransaction( + () -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); + DemoTenantEntitlementSnapshot demo = demos.readCurrent(request.tenantId()); + var head = prepared.selection().checkpoint(); + if (!demo.tenantAuthorityEventId().equals(head.eventId()) + || !demo.tenantAuthorityEventDigest().equals(head.eventDigest()) + || !demo.canonicalTenantId().equals(head.tenantId()) + || demo.tenantAuthorityGeneration() != head.tenantAuthorityGeneration() + || !demo.tenantAuthorityOutboxStreamKey().equals(head.outboxStreamKey()) + || demo.tenantAuthorityOutboxSequence() != head.outboxSequence() + || demo.tenantBillingSequence() != head.tenantBillingSequence() + || !demo.eventId().equals(head.tenantBillingEventId()) + || !demo.eventDigest().equals(head.tenantBillingEventDigest()) + || demo.tenantAuthoritySourceVersion() != head.tenantAuthoritySourceVersion()) { + throw unavailable(); + } + requireTenantSource( + player.snapshot(), + demo.canonicalTenantId(), + demo.tenantAuthorityGeneration(), + demo.tenantBillingSequence(), + demo.tenantAuthorityOutboxStreamKey(), + demo.tenantAuthorityOutboxSequence(), + demo.tenantAuthorityEventId(), + demo.tenantAuthorityEventDigest()); + Instant capturedAt = now(); + requireCurrentTimes(player, capturedAt); + return capture( + request, + player, + target, + facts( + "NON_PAID_DEMO", + null, + demo.gameplayAvailable(), + demo.allowPublicJoin(), + demo.allowNewGameplayBindings(), + demo.allowNewInstanceStarts(), + demo.quotas().maxActiveSessions(), + demo.quotas().maxConcurrentGameInstances(), + demo.quotas().maxStorageBytes(), + demo.entitlementVersion(), + demo.tenantBillingSequence(), + demo.tenantAuthorityGeneration()), + demo.snapshotIdentity(), + capturedAt, + null); + }); + } + + private VerifiedCaller verifyCaller(Request request, String token) { + Objects.requireNonNull(request, "Player entitlement request is required"); + requireNoAmbientTransaction(); + if (!expectedWorkload.equals(request.authenticatedCallerWorkload()) + || !namespace.equals(request.target().targetNamespace()) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null) throw unavailable(); + VerifiedCaller caller = callers.verifyPresentedCompactToken(token); + if (!expectedWorkload.equals(caller.identity().callerWorkload()) + || !request.target().accountId().equals(caller.identity().accountId())) throw unavailable(); + return caller; + } + + private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) { + UUID accountId = caller.identity().accountId(); + var account = + accounts + .findByAccountUuidForUpdate(accountId) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + if (!accountId.equals(account.getAccountUuid())) throw unavailable(); + CommittedCandidateVerificationData current = + issuances + .readCurrentCommittedCandidateByJti(caller.identity().tokenJti()) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + if (!CommittedCandidateVerificationData.hasSameOwnerEvidence( + caller.currentCandidate(), current)) { + throw unavailable(); + } + Snapshot snapshot = memberships.readCurrent(accountId, request.tenantId()); + RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot); + var authority = current.authoritySnapshot(); + var tuple = snapshot.authorityTuple(); + var expectedCutoff = + authority + .accountSecurityCutoff() + .map( + cutoff -> + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + var actualCutoff = + tuple + .accountSecurityCutoff() + .map( + cutoff -> + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + if (!ISSUER.equals(snapshot.issuerId()) + || !accountId.toString().equals(snapshot.accountId()) + || !request.tenantId().toString().equals(snapshot.tenantId()) + || !accountId.equals(authority.accountId()) + || !Long.toString(authority.issuerGeneration()).equals(tuple.issuerAuthGeneration()) + || !Long.toString(authority.accountGeneration()).equals(tuple.accountAuthorityGeneration()) + || !Long.toString(authority.issuanceFence()).equals(snapshot.issuanceFence()) + || !expectedCutoff.equals(actualCutoff) + || !tuple.privateRealmGrantVersions().isEmpty()) { + throw unavailable(); + } + var verifiedScope = + scopes + .findCanonical(request.connectScopeId()) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + CanonicalConnectScopeEvidence scope = + scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(request.connectScopeId())) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + if (!"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || scope.tenantProvenance().kind() != TenantProvenanceKind.FRESH_GAME_DESIGN + || scope.tenantProvenance().legacyTenantId() != null + || !accountId.equals(scope.accountUuid()) + || !request.tenantId().equals(scope.tenantUuid()) + || !AccountJoinDigest.scopeV2(verifiedScope).equals(scope.scopeDigest()) + || !Objects.equals(account.getId(), scope.privateAccountId())) { + throw unavailable(); + } + if (!request.target().equals(selector(request, scope))) throw unavailable(); + return new CurrentPlayer(snapshot, scope, current); + } + + private static void requireTenantSource( + Snapshot snapshot, + UUID tenantId, + long generation, + long billingSequence, + String stream, + long sequence, + UUID eventId, + String eventDigest) { + String tenant = snapshot.tenantId(); + TenantBillingCutoff cutoff = + new TenantBillingCutoff( + Long.toString(generation), + Long.toString(billingSequence), + stream, + Long.toString(sequence)); + if (!tenant.equals(tenantId.toString()) + || !TenantAuthorityEventV1Codec.streamKey(tenantId).equals(stream) + || !snapshot + .authorityTuple() + .tenantAuthorityGeneration() + .equals(Map.of(tenant, Long.toString(generation))) + || !snapshot + .authorityTuple() + .tenantBillingCutoff() + .filter(Map.of(tenant, cutoff)::equals) + .isPresent() + || snapshot.sourceEvidence().stream() + .noneMatch( + source -> + stream.equals(source.outboxStreamKey()) + && Long.toString(sequence).equals(source.outboxSequence()) + && eventId.toString().equals(source.eventId()) + && eventDigest.equals(source.eventDigest()))) { + throw unavailable(); + } + } + + private static void requireFreshReceipt( + Request request, AccountHostingSubscriptionCurrentReceipt receipt, Instant now) { + if (!request.tenantId().equals(receipt.current().tenantId()) + || receipt.evaluatedAt() == null + || receipt.validUntil() == null + || now.isBefore(receipt.evaluatedAt()) + || !now.isBefore(receipt.validUntil())) { + throw unavailable(); + } + } + + private static void requireCurrentTimes(CurrentPlayer player, Instant evaluatedAt) { + CanonicalConnectScopeEvidence scope = player.scope(); + var identity = player.issuance().identity(); + if (evaluatedAt.isBefore(Instant.parse(scope.evaluatedAt())) + || !evaluatedAt.isBefore(Instant.parse(scope.connectScopeExpiresAt())) + || evaluatedAt.getEpochSecond() < identity.notBeforeEpochSecond() + || evaluatedAt.getEpochSecond() >= identity.expiresAtEpochSecond()) { + throw unavailable(); + } + } + + private T inSourceTransaction(Supplier action) { + requireNoAmbientTransaction(); + return Objects.requireNonNull( + transaction.execute( + status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw unavailable(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + }); + return Objects.requireNonNull(action.get()); + })); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable"); + } + + private void requireSameHead(Request request, SourceSelection selected) { + SourceSelection current = sources.readCurrentSourceSelection(request.tenantId()); + if (selected.kind() != current.kind() || !selected.matches(current.checkpoint())) + throw unavailable(); + } + + /** Trusted method-authorized workload assertion; construction does not authenticate a peer. */ + public record Request( + RetainedTargetSelector target, String connectScopeId, String authenticatedCallerWorkload) { + public Request { + Objects.requireNonNull(target, "Exact resolved target selectors are required"); + if (connectScopeId == null || connectScopeId.isBlank() || connectScopeId.length() > 16384) + throw new IllegalArgumentException("Bounded opaque connect scope is required"); + GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) + .filter( + peer -> + peer.uri().equals(authenticatedCallerWorkload) + && "game-session-service".equals(peer.service())) + .orElseThrow( + () -> new IllegalArgumentException("Exact Game Session workload is required")); + } + + public UUID tenantId() { + return target.tenantId(); + } + + public UUID requestId() { + return target.readRequestId(); + } + + @Override + public String toString() { + return "PlayerAdmissionEntitlementRequest[redacted]"; + } + } + + private static RetainedTargetSelector selector( + Request request, CanonicalConnectScopeEvidence scope) { + return new RetainedTargetSelector( + request.requestId(), + scope.accountUuid(), + request.target().targetNamespace(), + scope.tenantUuid(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceUuid(), + scope.playableStateScope(), + scope.gameInstanceUuid(), + scope.catalogRevision(), + scope.pointerVersion()); + } + + private PublishedRealmEvidence readProtectedTarget( + Request request, CanonicalConnectScopeEvidence scope) { + requireNoAmbientTransaction(); + var selector = selector(request, scope); + var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); + if (!selector.equals(resolved.selector())) throw unavailable(); + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + var result = + Objects.requireNonNull(targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); + if (!resolved.strictSelector().equals(result.selector()) + || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); + return result; + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Request request, + CurrentPlayer player, + PublishedRealmEvidence target, + Map facts, + String entitlementSourceDigest, + Instant time, + Instant paidReceiptValidUntil) { + var scope = player.scope(); + var current = target.currentTarget(); + Map binding = new LinkedHashMap<>(); + binding.put("targetClass", "PUBLIC_PRODUCTION"); + binding.put("characterCreationPolicy", "PRESEEDED_ONLY"); + binding.put("targetNamespace", current.targetNamespace()); + binding.put("tenantId", scope.tenantUuid().toString()); + binding.put("tenantSlug", scope.tenantSlug()); + binding.put("worldSlug", scope.worldSlug()); + binding.put("realmId", scope.realmId().toString()); + binding.put("realmSlug", scope.realmSlug()); + binding.put("playableStateNamespaceId", scope.playableStateNamespaceUuid().toString()); + binding.put("playableStateScope", scope.playableStateScope()); + binding.put("gameInstanceId", scope.gameInstanceUuid().toString()); + binding.put("canonicalVersionId", current.canonicalVersionId().toString()); + binding.put("catalogRevision", Long.toString(scope.catalogRevision())); + binding.put("pointerVersion", Long.toString(scope.pointerVersion())); + binding.put("activeWorldEpoch", Long.toString(current.activeWorldEpoch())); + binding.put("evaluatedAt", scope.evaluatedAt()); + binding.put("connectScopeExpiresAt", scope.connectScopeExpiresAt()); + var caller = player.issuance(); + var world = target.worldLifecycleEvidence(); + Map sources = new LinkedHashMap<>(); + sources.put("callerTokenJti", caller.identity().tokenJti().toString()); + sources.put( + "callerTokenExpiresAt", + Instant.ofEpochSecond(caller.identity().expiresAtEpochSecond()).toString()); + sources.put( + "paidReceiptValidUntil", + paidReceiptValidUntil == null ? null : paidReceiptValidUntil.toString()); + sources.put("callerTokenSha256", caller.tokenSha256()); + sources.put("callerRegistryRecordSha256", caller.canonicalRegistryRecordSha256()); + sources.put("callerCommitProofSha256", caller.commitProofSha256()); + sources.put("callerContextId", caller.identity().callerContextId().toString()); + sources.put("callerOperationId", caller.identity().operationId().toString()); + sources.put("scopeDigest", scope.scopeDigest()); + sources.put("entitlementSourceDigest", entitlementSourceDigest); + sources.put( + "admissionPointerSnapshotDigest", target.sourceEvidence().admissionPointerSnapshotDigest()); + sources.put( + "gameSessionOwnerProofDigest", + target.sourceEvidence().gameSessionOwnerProof().proofDigest()); + sources.put( + "publishedPolicySetDigest", + target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); + sources.put( + "worldLifecycleDigest", + RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); + sources.put("worldCaptureId", world.captureId().toString()); + sources.put("worldRowVersion", Long.toString(world.rowVersion())); + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.requestId(), + request.authenticatedCallerWorkload(), + request.connectScopeId(), + player.snapshot(), + binding, + facts, + sources, + time); + } + + private static Map facts( + String kind, + String status, + boolean gameplay, + boolean join, + boolean bindings, + boolean starts, + long sessions, + long instances, + long storage, + long version, + long sequence, + long generation) { + Map result = new LinkedHashMap<>(); + result.put("sourceKind", kind); + result.put("subscriptionStatus", status); + result.put("provisioningStatus", null); + result.put("gameplayAvailable", gameplay); + result.put("allowPublicJoin", join); + result.put("allowNewGameplayBindings", bindings); + result.put("allowNewInstanceStarts", starts); + result.put( + "quotas", + Map.of( + "maxActiveSessions", + Long.toString(sessions), + "maxConcurrentGameInstances", + Long.toString(instances), + "maxStorageBytes", + Long.toString(storage))); + result.put("entitlementVersion", Long.toString(version)); + result.put("tenantBillingSequence", Long.toString(sequence)); + result.put("tenantAuthorityGeneration", Long.toString(generation)); + return result; + } + + private record Prepared(CurrentPlayer player, SourceSelection selection) {} + + private record CurrentPlayer( + Snapshot snapshot, + CanonicalConnectScopeEvidence scope, + CommittedCandidateVerificationData issuance) {} +} 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 cd964043bb..bdf3f17b00 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 @@ -139,13 +139,13 @@ public void issueDirectTextConnectScope( try { requireGameSessionPeer(); var context = request.getPlayerContext(); - long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID tenantId = requireCanonicalUuid(request.getTenantId(), "tenantId"); UUID realmId = requireCanonicalRealmId(request.getRealmId()); - long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); - if (requirePositiveRequestId(context.getTenantId(), "tenantId") != tenantId + UUID gameInstanceId = requireCanonicalUuid(request.getGameInstanceId(), "gameInstanceId"); + if (!requireCanonicalUuid(context.getTenantId(), "tenantId").equals(tenantId) || !requireCanonicalRealmId(context.getRealmId()).equals(realmId) - || requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId") - != gameInstanceId + || !requireCanonicalUuid(context.getGameInstanceId(), "gameInstanceId") + .equals(gameInstanceId) || !context.getPlayableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) || !context.getPlayableStateScope().equals(request.getPlayableStateScope())) { throw new InvalidRequestException("Player context and selected realm disagree", null); @@ -159,7 +159,8 @@ public void issueDirectTextConnectScope( realmId, requireText(request.getWorldSlug(), "worldSlug"), requireText(request.getRealmSlug(), "realmSlug"), - requireText(request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireCanonicalUuid( + request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), requireText(request.getPlayableStateScope(), "playableStateScope"), gameInstanceId, request.getCatalogRevision(), @@ -208,17 +209,18 @@ public void joinPublicProductionMembership( new JoinPublicProductionRequest( requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); if (!request.getPlayerContext().getAccountId().equals(result.accountId()) - || result.tenantId() != caller.tenantId()) { + || !result.tenantId().equals(caller.tenantId())) { throw new IllegalStateException("Account JOIN result does not match the validated caller"); } response .setSuccess(result.success()) .setOutcomeCode(result.outcomeCode()) .setAccountId(result.accountId()) - .setTenantId(Long.toString(result.tenantId())) + .setTenantId(result.tenantId().toString()) .setMembershipId(Long.toString(result.membershipId())) .setMembershipVersion(result.membershipVersion()) .setMembershipAuthorityGeneration(result.membershipAuthorityGeneration()) + .setGameplayAdmissionAllowed(result.gameplayAdmissionAllowed()) .setReplayed(result.replayed()); } catch (AdminAuthorizationException ex) { response.setError( @@ -302,9 +304,13 @@ private void requireCallerAccountSubject(UUID accountUuid) { } private static UUID requireCanonicalAccountUuid(String value) { + return requireCanonicalUuid(value, "accountId"); + } + + private static UUID requireCanonicalUuid(String value, String field) { UUID accountUuid = AccountUuidText.parseOrNull(value); if (accountUuid == null) { - throw new InvalidRequestException("accountId must be a canonical non-nil UUID", null); + throw new InvalidRequestException(field + " must be a canonical non-nil UUID", null); } return accountUuid; } @@ -312,57 +318,23 @@ private static UUID requireCanonicalAccountUuid(String value) { private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { UUID accountUuid = requireCanonicalAccountUuid(context.getAccountId()); - long tenantId = requirePositiveRequestId(context.getTenantId(), "tenantId"); + UUID tenantId = requireCanonicalUuid(context.getTenantId(), "tenantId"); UUID realmId = requireCanonicalRealmId(context.getRealmId()); - String namespaceId = - requireCanonicalPlayableStateNamespaceId(context.getPlayableStateNamespaceId()); + UUID namespaceId = + requireCanonicalUuid(context.getPlayableStateNamespaceId(), "playableStateNamespaceId"); String scope = requireText(context.getPlayableStateScope(), "playableStateScope"); - long gameInstanceId = requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"); - String sessionId = requireText(context.getSessionId(), "sessionId"); - String requestId = requireText(context.getRequestId(), "requestId"); - long accountStorageId = accountService.resolveAccountStorageId(accountUuid); - if (accountStorageId <= 0L) { - throw new IllegalStateException("Account UUID did not resolve to a persisted owner"); + if (!java.util.Set.of("SHARED", "ISOLATED").contains(scope)) { + throw new InvalidRequestException("playableStateScope must be SHARED or ISOLATED", null); } + UUID gameInstanceId = requireCanonicalUuid(context.getGameInstanceId(), "gameInstanceId"); + String sessionId = requireCanonicalUuid(context.getSessionId(), "sessionId").toString(); + String requestId = requireText(context.getRequestId(), "requestId"); return new DirectTextCallerContext( - accountStorageId, - tenantId, - realmId, - namespaceId, - scope, - gameInstanceId, - sessionId, - requestId); + accountUuid, tenantId, realmId, namespaceId, scope, gameInstanceId, sessionId, requestId); } private UUID requireCanonicalRealmId(String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("realmId is required"); - } - try { - UUID realmId = UUID.fromString(value); - if (!realmId.toString().equals(value)) { - throw new IllegalArgumentException("realmId must be a canonical UUID"); - } - return realmId; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("realmId must be a canonical UUID", ex); - } - } - - private String requireCanonicalPlayableStateNamespaceId(String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("playableStateNamespaceId is required"); - } - try { - UUID namespaceId = UUID.fromString(value); - if (!namespaceId.toString().equals(value)) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); - } - return value; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); - } + return requireCanonicalUuid(value, "realmId"); } private String requireText(String value, String fieldName) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java new file mode 100644 index 0000000000..2ddf42719a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account owner receiver. No component annotation, capacity commit, World hold or + * gameplay admission. + */ +public final class AccountPlayerAdmissionEntitlementGrpcService + extends AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceImplBase { + private final AccountPlayerAdmissionEntitlementOwner owner; + private final String namespace; + private final AccountPlayerAdmissionEntitlementWorkloadGuard guard; + + public AccountPlayerAdmissionEntitlementGrpcService( + AccountPlayerAdmissionEntitlementOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + this.guard = new AccountPlayerAdmissionEntitlementWorkloadGuard(namespace); + this.namespace = namespace; + } + + /** + * Explicit private composition, requiring real client certificates. Returns an unstarted server. + */ + public Server createUnregisteredServer( + String address, KeyManagerFactory keys, TrustManagerFactory trust) { + var factory = + new BoundedGrpcServerFactory( + Objects.requireNonNull(address), + List.of(), + Objects.requireNonNull(keys), + Objects.requireNonNull(trust), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String authenticatedCaller; + try { + authenticatedCaller = guard.requireAuthenticatedGameSessionCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + final RuntimePlayerAdmissionEntitlementGrpcCodec.PresentedRequest presented; + if (wire == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + try { + presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException invalid) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + var request = presented.request(); + if (!namespace.equals(request.target().targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + final ReadPlayerAdmissionEntitlementResponse response; + try { + var sourceRequest = + new AccountPlayerAdmissionEntitlementOwner.Request( + request.target(), request.connectScopeId(), authenticatedCaller); + var evidence = owner.evaluate(sourceRequest, presented.initialLoginJwt()); + response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, evidence); + } catch (RuntimeException unavailableSource) { + // No positive evidence, alternate source, or exception details escape an unavailable + // evaluation. + fail(observer, Status.UNAVAILABLE); + return; + } + try { + observer.onNext(response); + } catch (RuntimeException callbackFailure) { + fail(observer, Status.INTERNAL); + return; + } + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status) { + observer.onError( + Status.fromCode(status.getCode()) + .withDescription("Player-admission entitlement evidence is unavailable") + .asRuntimeException()); + } +} 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 756f83b446..122e67a325 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 @@ -11,8 +11,10 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; +import java.time.Clock; import java.time.Instant; import java.time.LocalDateTime; +import java.util.Comparator; import java.util.HashMap; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -23,6 +25,9 @@ import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; @@ -31,10 +36,12 @@ import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; 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.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -75,14 +82,22 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository; import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; @@ -91,8 +106,12 @@ import net.firedevops.firemud.accountservice.repository.ProfileRepository; import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.Intent; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; @@ -104,11 +123,16 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; @@ -119,6 +143,7 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; @Service @@ -141,6 +166,10 @@ public class AccountServiceImpl implements AccountService { private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); private String gameplayDecoyPasswordVerifier; + private AccountPublicBootstrapWorldsOwner publicBootstrapWorldsOwner; + private AccountCanonicalPublicRealmScopeOwner canonicalPublicRealmScopeOwner; + private CanonicalScopeConsumers canonicalScopeConsumers; + private AccountBootstrapRosterReadClient accountBootstrapRosterReadClient; private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @@ -419,51 +448,714 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri Instant.ofEpochMilli(expiresAt).toString()); } - // Numeric retained billing history cannot authorize public discovery or admission. - // The complete canonical public facade is integrated in the receiving successor. + /** + * Explicit held composition only. The canonical source remains unregistered until its owning + * runtime boundary is qualified; absence never selects the retained numeric discovery path. + */ + @Autowired(required = false) + public void setPublicBootstrapWorldsOwner(AccountPublicBootstrapWorldsOwner owner) { + this.publicBootstrapWorldsOwner = Objects.requireNonNull(owner); + } + + // Bootstrap/JOIN orchestration deliberately has no transaction advice: NOT_SUPPORTED would + // still create empty synchronization. These entry points reject ambient SQL, while each + // canonical owner opens its own short transaction around owner-local state only. @Override @Timed(value = "account.bootstrap_worlds") public List listBootstrapWorlds(String bootstrapToken) { - throw publicBootstrapUnavailable(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Public bootstrap world discovery refuses ambient SQL"); + } + AccountPublicBootstrapWorldsOwner owner = publicBootstrapWorldsOwner; + if (owner == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical public-world discovery source is unavailable"); + } + return owner.listWorlds(bootstrapToken); + } + + /** + * Explicit held composition; the owner retains the signed V2 selector before publication. Its + * direct-text entry point authenticates the existing Game Session caller separately. + */ + @Autowired(required = false) + public void setCanonicalPublicRealmScopeOwner(AccountCanonicalPublicRealmScopeOwner owner) { + this.canonicalPublicRealmScopeOwner = Objects.requireNonNull(owner); + } + + /** Explicit composition of the existing canonical consumers; this does not register an issuer. */ + public void setCanonicalScopeConsumers( + AccountCanonicalConnectScopeReader reader, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + AccountCanonicalFirstJoinTerminalCoordinator firstJoin, + String namespace, + Clock clock) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + canonicalScopeConsumers = + new CanonicalScopeConsumers( + Objects.requireNonNull(reader), + Objects.requireNonNull(targets), + Objects.requireNonNull(tenantSources), + Objects.requireNonNull(demos), + Objects.requireNonNull(hosting), + Objects.requireNonNull(observer), + Objects.requireNonNull(firstJoin), + namespace, + Objects.requireNonNull(clock)); + } + + private CanonicalScopeConsumers requireCanonicalScopeConsumers() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Canonical scope consumers refuse ambient Account SQL"); + } + if (canonicalScopeConsumers == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical scope consumers are unavailable"); + } + return canonicalScopeConsumers; + } + + private Target readCanonicalScopeTarget( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + return readCanonicalScopePublishedTarget(consumers, scope).currentTarget(); + } + + private PublishedRealmEvidence readCanonicalScopePublishedTarget( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + try { + RetainedTargetSelector selector = + new RetainedTargetSelector( + UUID.randomUUID(), + scope.accountId(), + consumers.namespace(), + scope.tenantId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + var resolved = + Objects.requireNonNull( + consumers.targets().resolvePublishedRealmAdmissionTarget(selector)); + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .requireRetainedTargetMatches(selector, resolved.currentTarget()); + if (!selector.equals(resolved.selector())) + throw new IllegalStateException("Resolved selector differs"); + var published = + Objects.requireNonNull( + consumers.targets().readPublishedRealmAdmissionOwner(resolved.strictSelector())); + if (!resolved.strictSelector().equals(published.selector()) + || !resolved.currentTarget().equals(published.currentTarget())) { + throw new IllegalStateException( + "Published target differs from its resolved owner selectors"); + } + return published; + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", STALE_CONNECT_SCOPE_MESSAGE, failure); + } + } + + private Account lockCanonicalScopeAccount(CanonicalJoinScopeV2 scope) { + Account account = + accountRepository + .findByAccountUuidForUpdate(scope.accountId()) + .orElseThrow( + () -> new AuthenticationException("AUTH_UNAVAILABLE", "Account is unavailable")); + requireAccountStorageId(account, scope.accountId()); + requireAuthenticationEligible(account); + return account; + } + + private CanonicalJoinPreparation prepareCanonicalJoin( + CanonicalScopeConsumers consumers, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding) { + // Retain the exact policy-independent intent before any fallible source/provider work. + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); + }); + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + lockCanonicalScopeAccount(scope); + CanonicalJoinOperationEvidence operation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(operation.status())) { + return new CanonicalJoinPreparation(operation, null, null, null); + } + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return switch (source.kind()) { + case PAID_HOSTING -> + new CanonicalJoinPreparation( + operation, + source, + null, + consumers.hosting().prepareCurrentRead(scope.tenantId())); + case NON_PAID_DEMO -> + new CanonicalJoinPreparation( + operation, source, consumers.demos().readCurrent(scope.tenantId()), null); + }; + })); + } + + private CanonicalJoinResult commitCanonicalJoin( + CanonicalScopeConsumers consumers, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + CanonicalJoinPreparation prepared, + StripeHostingSubscriptionObserver.Result observation) { + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + if ("FAILED".equals(prepared.operation().status())) { + return new CanonicalJoinResult(prepared.operation().outcome(), null, false); + } + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant source changed"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + final long entitlementVersion; + if (prepared.fence() != null) { + AccountHostingSubscriptionCurrentReceipt receipt = + consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + entitlementVersion = receipt.entitlementVersion(); + } else { + DemoTenantEntitlementSnapshot demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + entitlementVersion = demo.entitlementVersion(); + } + accountJoinOperationRepository.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); + Optional member = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + boolean active = + member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); + if (!gameplayAvailable || (!active && !allowPublicJoin)) { + String outcome = + gameplayAvailable + ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" + : "TENANT_BILLING_BLOCKED"; + if ("PENDING".equals(prepared.operation().status())) { + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, outcome); + } + return new CanonicalJoinResult(outcome, null, false); + } + var committed = + consumers + .firstJoin() + .commitCanonicalJoin( + scope, + requestId, + callerBinding, + prepared.fence() == null ? null : consumers.hosting(), + prepared.fence(), + observation); + requireCanonicalScopeFresh(consumers, scope); + var currentMembership = + accountTenantMembershipRepository + .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) + .orElseThrow(); + if (currentMembership.getMembershipVersion() + != committed.terminalProof().membershipVersion() + || currentMembership.getMembershipAuthorityGeneration() + != committed.terminalProof().membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Canonical JOIN result differs from current membership"); + } + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + currentMembership.isGameplayAdmissionAllowed()); + })); + } + + private void requireCanonicalScopeFresh( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + Instant now = consumers.clock().instant(); + if (now.isBefore(Instant.parse(scope.evaluatedAt())) + || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + } + + private record CanonicalScopeConsumers( + AccountCanonicalConnectScopeReader reader, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + AccountCanonicalFirstJoinTerminalCoordinator firstJoin, + String namespace, + Clock clock) {} + + private record CanonicalJoinPreparation( + CanonicalJoinOperationEvidence operation, + SourceSelection source, + DemoTenantEntitlementSnapshot demo, + ReadFence fence) {} + + private record CanonicalJoinResult( + String outcome, CanonicalJoinTerminalProof proof, boolean gameplayAdmissionAllowed) {} + + /** Explicit non-admitting Entity projection; no default runtime client is registered here. */ + public void setAccountBootstrapRosterReadClient(AccountBootstrapRosterReadClient client) { + accountBootstrapRosterReadClient = Objects.requireNonNull(client); + } + + private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + try { + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return new BootstrapCharacterAuthority( + source, + membership, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO + ? consumers.demos().readCurrent(scope.tenantId()) + : null, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING + ? consumers.hosting().prepareCurrentRead(scope.tenantId()) + : null, + consumers.clock().instant()); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable", + failure); + } + })); + } + + private Optional + readBootstrapCharacterMembership(CanonicalJoinScopeV2 scope) { + try { + return accountTenantMembershipRepository + .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) + .map( + member -> + new AccountCanonicalPublicRealmScopeOwner.ExistingMembership( + member.getId(), + member.getLifecycleState(), + member.isGameplayAdmissionAllowed(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration())); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap membership source is unavailable", failure); + } + } + + private void requireBootstrapCharacterAuthority( + CanonicalScopeConsumers consumers, + CanonicalJoinScopeV2 scope, + BootstrapCharacterAuthority prepared, + StripeHostingSubscriptionObserver.Result observation) { + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + if (!prepared.membership().equals(membership)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap membership changed during discovery"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + try { + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new IllegalStateException("Bootstrap entitlement source changed"); + } + if (prepared.fence() != null) { + var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + } else { + Instant currentTime = consumers.clock().instant(); + if (currentTime.isBefore(prepared.observedAt()) + || !currentTime.isBefore(prepared.observedAt().plusSeconds(15))) { + throw new IllegalStateException( + "Original bootstrap entitlement observation expired"); + } + var demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + } + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable or changed", + failure); + } + if (!gameplayAvailable) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + if (membership.isEmpty() + || "INACTIVE".equals(membership.orElseThrow().lifecycleState())) { + throw new AuthenticationException( + allowPublicJoin ? "JOIN_REQUIRED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", + allowPublicJoin ? JOIN_REQUIRED_CHARACTERS_MESSAGE : "Public enrollment is closed"); + } + if (!"ACTIVE".equals(membership.orElseThrow().lifecycleState()) + || !membership.orElseThrow().gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", "Membership does not allow actor discovery"); + } + }); + } + + private record BootstrapCharacterAuthority( + SourceSelection source, + Optional membership, + DemoTenantEntitlementSnapshot demo, + ReadFence fence, + Instant observedAt) {} + + private StripeHostingSubscriptionObserver.Result observeBootstrapCharacterSource( + CanonicalScopeConsumers consumers, BootstrapCharacterAuthority prepared) { + if (prepared.fence() == null) return null; + try { + return consumers.observer().observe(prepared.fence().binding()); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Bootstrap provider source is unavailable", failure); + } + } + + private void requireSameBootstrapCaller(BootstrapContext original, String token) { + if (!original.equals(requireBootstrapContext(token))) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap caller changed during actor discovery"); + } } @Override @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { - throw publicBootstrapUnavailable(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Public bootstrap realm discovery refuses ambient SQL"); + } + AccountCanonicalPublicRealmScopeOwner owner = canonicalPublicRealmScopeOwner; + if (owner == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical public-realm scope source is unavailable"); + } + return owner.listRealmScopes(bootstrapToken, worldSlug).stream() + .map( + retained -> { + var target = retained.target(); + var scope = retained.scope(); + return new BootstrapRealmDto( + scope.worldSlug(), + scope.realmSlug(), + scope.realmId(), + target.realmDisplayName(), + scope.tenantId(), + scope.gameInstanceId(), + scope.pointerVersion(), + scope.catalogRevision(), + scope.playableStateNamespaceId(), + PlayableStateScope.valueOf("PLAYABLE_STATE_SCOPE_" + scope.playableStateScope()) + .name(), + scope.playableStateScope(), + target.characterCreationPolicy(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.connectScopeId()); + }) + .toList(); } @Override @Timed(value = "account.bootstrap_characters") public List listBootstrapCharacters( String bootstrapToken, String worldSlug, String realmSlug, String connectScopeId) { - throw publicBootstrapUnavailable(); + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); + AccountBootstrapRosterReadClient roster = accountBootstrapRosterReadClient; + if (roster == null) + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical Entity bootstrap discovery is unavailable"); + BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + CanonicalJoinScopeV2 scope = + consumers.reader().read(bootstrapContext.accountUuid(), connectScopeId); + if (!scope.worldSlug().equals(worldSlug) || !scope.realmSlug().equals(realmSlug)) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + if (!"SHARED".equals(scope.playableStateScope())) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); + } + PublishedRealmEvidence published = readCanonicalScopePublishedTarget(consumers, scope); + if (!"SHARED".equals(published.currentTarget().playableStateScope()) + || !"PRESEEDED_ONLY".equals(published.currentTarget().characterCreationPolicy())) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); + } + BootstrapCharacterAuthority prepared = prepareBootstrapCharacterAuthority(consumers, scope); + var observation = observeBootstrapCharacterSource(consumers, prepared); + requireBootstrapCharacterAuthority(consumers, scope, prepared, observation); + requireSameBootstrapCaller(bootstrapContext, bootstrapToken); + final List actors; + try { + actors = List.copyOf(roster.read(UUID.randomUUID(), scope.accountId(), published)); + } catch (io.grpc.StatusRuntimeException failure) { + String code = + failure.getStatus().getCode() == io.grpc.Status.Code.FAILED_PRECONDITION + ? "CONNECT_SCOPE_MISMATCH" + : "AUTH_UNAVAILABLE"; + throw new AuthenticationException( + code, "Entity bootstrap discovery is unavailable or changed", failure); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Entity bootstrap discovery is malformed or unavailable", failure); + } + PublishedRealmEvidence current = readCanonicalScopePublishedTarget(consumers, scope); + if (!published.currentTarget().equals(current.currentTarget()) + || !java.util.Arrays.equals( + published.sourceEvidence().publishedPolicySetEvidence().canonicalBytes(), + current.sourceEvidence().publishedPolicySetEvidence().canonicalBytes())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + requireSameBootstrapCaller(bootstrapContext, bootstrapToken); + var finalObservation = observeBootstrapCharacterSource(consumers, prepared); + requireBootstrapCharacterAuthority(consumers, scope, prepared, finalObservation); + requireCanonicalScopeFresh(consumers, scope); + requireSameBootstrapCaller(bootstrapContext, bootstrapToken); + return actors.stream() + .sorted( + Comparator.comparing(AccountBootstrapRosterReadClient.Actor::displayName) + .thenComparing(actor -> actor.characterId().toString())) + .map( + actor -> + new BootstrapCharacterDto( + actor.characterId().toString(), + actor.displayName(), + actor.level(), + scope.playableStateScope(), + published.currentTarget().characterCreationPolicy())) + .toList(); } @Override @Timed(value = "account.public_production_join") public JoinPublicProductionResult joinPublicProduction( String bootstrapToken, JoinPublicProductionRequest request) { - throw publicBootstrapUnavailable(); + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); + BootstrapContext caller = requireBootstrapContext(bootstrapToken); + Claims callerClaims = + requireSignedTokenClaims( + bootstrapToken, + "player-bootstrap", + "CONNECT_CONTEXT_INVALID", + "Missing bootstrap token", + "Invalid bootstrap token"); + String callerBinding; + try { + callerBinding = JwtClaims.requireText(callerClaims.get("jti"), "jti"); + } catch (IllegalArgumentException ex) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); + } + return joinCanonicalPublicProduction( + consumers, + caller.accountUuid(), + callerBinding, + request, + () -> { + BootstrapContext current = requireBootstrapContext(bootstrapToken); + if (!caller.equals(current)) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Bootstrap caller changed"); + } + }); + } + + private JoinPublicProductionResult joinCanonicalPublicProduction( + CanonicalScopeConsumers consumers, + UUID accountUuid, + String callerBinding, + JoinPublicProductionRequest request, + Runnable recheckCaller) { + if (request == null + || !StringUtils.hasText(request.connectScopeId()) + || !StringUtils.hasText(request.requestId())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + if (request.requestId().length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { + throw new AuthenticationException( + "INVALID_ARGUMENT", "JOIN requestId exceeds the maximum length"); + } + CanonicalJoinScopeV2 scope = consumers.reader().read(accountUuid, request.connectScopeId()); + try { + CanonicalJoinPreparation prepared = + prepareCanonicalJoin(consumers, scope, request.requestId(), callerBinding); + Target target = readCanonicalScopeTarget(consumers, scope); + // The SDK's sealed result crosses source transactions; provider I/O never runs under SQL. + StripeHostingSubscriptionObserver.Result observation = + prepared.fence() == null + ? null + : consumers.observer().observe(prepared.fence().binding()); + if (!target.equals(readCanonicalScopeTarget(consumers, scope))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + recheckCaller.run(); + CanonicalJoinResult committed = + commitCanonicalJoin( + consumers, scope, request.requestId(), callerBinding, prepared, observation); + requireCanonicalScopeFresh(consumers, scope); + CanonicalJoinTerminalProof proof = committed.proof(); + // Publish only after the owner transaction has committed; response loss is exact-retryable. + return new JoinPublicProductionResult( + proof != null, + committed.outcome(), + scope.accountId().toString(), + scope.tenantId(), + proof == null ? 0L : proof.membershipId(), + proof == null ? 0L : proof.membershipVersion(), + proof == null ? 0L : proof.membershipAuthorityGeneration(), + committed.gameplayAdmissionAllowed(), + !"PENDING".equals(prepared.operation().status())); + } catch (AccountJoinOperationRepository.CanonicalJoinOperationConflictException failure) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID conflicts", failure); + } catch (RuntimeException failure) { + String code = + failure instanceof AuthenticationException authentication + ? authentication.getCode() + : "ENTITLEMENT_UNAVAILABLE"; + recordCanonicalJoinFailure(scope, request.requestId(), callerBinding, code); + if (failure instanceof AuthenticationException authentication) throw authentication; + throw new AuthenticationException( + code, "Canonical JOIN authority is unavailable; retry the same request", failure); + } + } + + private void recordCanonicalJoinFailure( + CanonicalJoinScopeV2 scope, String requestId, String callerBinding, String failureCode) { + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + Optional found = + accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); + if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; + if (List.of("CONNECT_SCOPE_MISMATCH", "CONNECT_SCOPE_INVALID").contains(failureCode)) { + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, failureCode); + } else { + String retryCode = + List.of( + "ADMISSION_POINTER_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "AUTH_UNAVAILABLE") + .contains(failureCode) + ? failureCode + : "AUTH_UNAVAILABLE"; + accountJoinOperationRepository.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, "UNAVAILABLE", retryCode); + } + }); } @Override @Timed(value = "account.direct_text_connect_scope") public DirectTextJoinScope issueDirectTextConnectScope( DirectTextCallerContext caller, DirectTextJoinTarget target) { - throw publicBootstrapUnavailable(); + if (canonicalPublicRealmScopeOwner == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical scope producer is unavailable"); + } + CanonicalJoinScopeV2 scope = + canonicalPublicRealmScopeOwner.issueDirectTextScope(caller, target).scope(); + return new DirectTextJoinScope( + scope.connectScopeId(), scope.connectScopeExpiresAt(), scope.evaluatedAt()); } @Override @Timed(value = "account.public_production_join_internal") public JoinPublicProductionResult joinPublicProductionFromGameSession( DirectTextCallerContext caller, JoinPublicProductionRequest request) { - throw publicBootstrapUnavailable(); - } - - private AuthenticationException publicBootstrapUnavailable() { - return new AuthenticationException( - "AUTH_UNAVAILABLE", "Canonical public gameplay authority is unavailable"); + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); + requireCanonicalDirectPeer(consumers); + if (caller == null + || caller.accountId() == null + || NIL_ACCOUNT_UUID.equals(caller.accountId()) + || !StringUtils.hasText(caller.sessionId()) + || AccountUuidText.parseOrNull(caller.sessionId()) == null + || !StringUtils.hasText(caller.requestId()) + || request == null + || !caller.requestId().equals(request.requestId())) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); + } + CanonicalJoinScopeV2 scope = + consumers.reader().read(caller.accountId(), request.connectScopeId()); + if (!scope.tenantId().equals(caller.tenantId()) + || !scope.realmId().equals(caller.realmId()) + || !scope.playableStateNamespaceId().equals(caller.playableStateNamespaceId()) + || !scope.playableStateScope().equals(caller.playableStateScope()) + || !scope.gameInstanceId().equals(caller.gameInstanceId())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + return joinCanonicalPublicProduction( + consumers, + caller.accountId(), + caller.sessionId(), + request, + () -> requireCanonicalDirectPeer(consumers)); + } + + private void requireCanonicalDirectPeer(CanonicalScopeConsumers consumers) { + var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-session-service") + || !peer.isInNamespace(consumers.namespace())) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Exact Game Session workload is required"); + } } private String responseAccountUuid(Long accountId) { @@ -498,7 +1190,11 @@ private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean loc @Override @Timed(value = "account.connect_token") public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request) { - throw publicBootstrapUnavailable(); + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); + BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + consumers.reader().read(bootstrapContext.accountUuid(), request.connectScopeId()); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical gameplay connect-token authority is unavailable"); } @Override diff --git a/services/account-service/src/main/resources/db/migration/V1035__canonical_join_failure_and_attempt_diagnostics.sql b/services/account-service/src/main/resources/db/migration/V1035__canonical_join_failure_and_attempt_diagnostics.sql new file mode 100644 index 0000000000..8f8e183945 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1035__canonical_join_failure_and_attempt_diagnostics.sql @@ -0,0 +1,440 @@ +-- Extend only the canonical V2 journal. V1 rows and applied migrations are unchanged. +-- Bound policy bytes remain immutable while PENDING diagnostics can describe an unavailable +-- retry or exact-policy recovery. FAILED retains intent/scope and optional original policy, +-- never membership/event/audit success evidence. Both terminal states remain immutable. +/* [jooq ignore start] */ +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_operation_representation_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_representation_check CHECK ( + (operation_representation_version = 1 AND scope_digest_version = 1 + AND target_class IS NULL AND account_uuid IS NULL AND tenant_uuid IS NULL + AND tenant_slug IS NULL AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL) + OR + (operation_representation_version = 2 AND scope_digest_version = 2 + AND request_id IS NOT NULL AND account_id IS NOT NULL + AND verified_caller_binding IS NOT NULL AND scope_token_hash IS NOT NULL + AND connect_scope_digest IS NOT NULL AND realm_id IS NOT NULL + AND world_slug IS NOT NULL AND realm_slug IS NOT NULL + AND playable_state_scope IS NOT NULL AND catalog_revision IS NOT NULL + AND pointer_version IS NOT NULL AND intent_digest_version = 2 + AND intent_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_authority_availability IS NOT NULL + AND last_attempt_authority_availability IS NOT NULL + AND caller_bound_authority_invalidated IS FALSE + AND btrim(request_id) <> '' AND verified_caller_binding <> '' + AND scope_token_hash ~ '^sha256:[0-9a-f]{64}$' + AND target_class = 'PUBLIC_PRODUCTION' + AND tenant_id IS NULL AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug <> '' AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND connect_scope_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING' AND outcome IS NULL AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome = 'JOINED' + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version = 2 + AND outcome_membership_authority_generation = 1))) + ); + +ALTER TABLE account_join_operations DROP CONSTRAINT account_join_canonical_terminal_proof_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_canonical_terminal_proof_check CHECK ( + (operation_representation_version = 1 + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status IN ('PENDING', 'FAILED') + AND ((status = 'PENDING' AND outcome IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE'))) AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status = 'COMMITTED' + AND outcome = 'JOINED' + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version = 2 + AND outcome_membership_authority_generation = 1 + AND membership_authority_outbox_stream_key IS NOT NULL + AND membership_authority_outbox_stream_key = + 'account:auth-authority:v1:membership/' || account_uuid::TEXT || '/' || tenant_uuid::TEXT + AND membership_authority_outbox_sequence IS NOT NULL + AND membership_authority_outbox_sequence = 1 + AND membership_authority_event_id IS NOT NULL + AND btrim(membership_authority_event_id) <> '' + AND membership_authority_event_digest IS NOT NULL + AND membership_authority_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND join_audit_event_id IS NOT NULL + AND join_audit_event_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND join_audit_payload_digest IS NOT NULL + AND join_audit_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND join_audit_occurred_at IS NOT NULL) + ); + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_v2_attempt_diagnostics_check CHECK ( + operation_representation_version = 1 OR ( + operation_representation_version = 2 AND ( + (last_attempt_failure_code IS NULL AND ( + (request_digest IS NULL + AND entitlement_authority_availability = 'NOT_EVALUATED' + AND last_attempt_authority_availability = 'NOT_EVALUATED') + OR (request_digest IS NOT NULL + AND entitlement_authority_availability = 'AVAILABLE' + AND last_attempt_authority_availability = 'AVAILABLE'))) + OR (status = 'PENDING' AND last_attempt_failure_code IS NOT NULL + AND last_attempt_failure_code IN ('AUTH_UNAVAILABLE', 'ENTITLEMENT_UNAVAILABLE', 'ADMISSION_POINTER_UNAVAILABLE') + AND last_attempt_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') + AND (request_digest IS NOT NULL + OR entitlement_authority_availability = last_attempt_authority_availability)) + ) + ) + ); + +CREATE OR REPLACE FUNCTION guard_account_join_operation_identity() RETURNS trigger AS $$ +DECLARE + scope_source_matches BOOLEAN := FALSE; + membership_matches BOOLEAN := FALSE; + pair_matches BOOLEAN := FALSE; + authority_event_matches BOOLEAN := FALSE; + audit_envelope_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.operation_representation_version = 2 THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.operation_representation_version = 1 THEN + RETURN NEW; + END IF; + IF NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.scope_digest_version IS DISTINCT FROM 2 + OR NEW.intent_digest_version IS DISTINCT FROM 2 + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.request_digest_version IS NOT NULL OR NEW.request_digest IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN operation must start as an exact pending intent' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_connect_scope_records scope_row + WHERE scope_row.scope_token_hash = NEW.scope_token_hash + AND scope_row.scope_digest_version = 2 + AND scope_row.snapshot_digest = NEW.connect_scope_digest + AND scope_row.account_id = NEW.account_id + AND scope_row.account_uuid = NEW.account_uuid + AND scope_row.target_class = NEW.target_class + AND scope_row.tenant_id IS NULL + AND scope_row.tenant_uuid = NEW.tenant_uuid + AND scope_row.tenant_slug = NEW.tenant_slug + AND scope_row.realm_id = NEW.realm_id + AND scope_row.world_slug = NEW.world_slug + AND scope_row.realm_slug = NEW.realm_slug + AND scope_row.playable_state_namespace_id IS NULL + AND scope_row.playable_state_namespace_uuid = NEW.playable_state_namespace_uuid + AND scope_row.playable_state_scope = NEW.playable_state_scope + AND scope_row.game_instance_id IS NULL + AND scope_row.game_instance_uuid = NEW.game_instance_uuid + AND scope_row.catalog_revision = NEW.catalog_revision + AND scope_row.pointer_version = NEW.pointer_version + ) INTO scope_source_matches; + IF NOT scope_source_matches THEN + RAISE EXCEPTION 'Canonical JOIN operation has no exact persisted scope source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version = 1 THEN + IF NEW.operation_representation_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'Retained JOIN operation evidence cannot change representation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version <> 2 + OR NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.verified_caller_binding IS DISTINCT FROM OLD.verified_caller_binding + OR NEW.scope_token_hash IS DISTINCT FROM OLD.scope_token_hash + OR NEW.connect_scope_digest IS DISTINCT FROM OLD.connect_scope_digest + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_slug IS DISTINCT FROM OLD.realm_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.catalog_revision IS DISTINCT FROM OLD.catalog_revision + OR NEW.pointer_version IS DISTINCT FROM OLD.pointer_version + OR NEW.intent_digest_version IS DISTINCT FROM OLD.intent_digest_version + OR NEW.intent_digest IS DISTINCT FROM OLD.intent_digest + OR NEW.scope_digest_version IS DISTINCT FROM OLD.scope_digest_version + OR NEW.target_class IS DISTINCT FROM OLD.target_class + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_slug IS DISTINCT FROM OLD.tenant_slug + OR NEW.playable_state_namespace_uuid IS DISTINCT FROM OLD.playable_state_namespace_uuid + OR NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Canonical JOIN operation intent evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.status IN ('COMMITTED', 'FAILED') THEN + RAISE EXCEPTION 'Terminal canonical JOIN receipt is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF OLD.status IS DISTINCT FROM 'PENDING' THEN + RAISE EXCEPTION 'Canonical JOIN operation has unsupported prior status' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.request_digest IS NULL THEN + IF NEW.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.allow_public_join IS NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN policy binding is incomplete' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.status = 'FAILED' THEN + IF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Unbound failed canonical JOIN cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability NOT IN ('UNAVAILABLE', 'NOT_EVALUATED') + OR NEW.last_attempt_authority_availability IS DISTINCT FROM NEW.entitlement_authority_availability + OR NEW.last_attempt_failure_code IS NULL + OR NEW.last_attempt_failure_code NOT IN ('AUTH_UNAVAILABLE', 'ENTITLEMENT_UNAVAILABLE', 'ADMISSION_POINTER_UNAVAILABLE') THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_authority_availability IS DISTINCT FROM OLD.entitlement_authority_availability + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join THEN + RAISE EXCEPTION 'Canonical JOIN available policy evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.status = 'FAILED' THEN + IF NEW.outcome IS NULL OR NEW.outcome NOT IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Failed canonical JOIN must retain original policy and no success proof' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending canonical JOIN cannot carry terminal receipt evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' + OR NEW.outcome IS DISTINCT FROM 'JOINED' + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.allow_public_join IS DISTINCT FROM TRUE + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.request_digest IS NULL + OR NEW.request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_attempt_failure_code IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.membership_id IS NULL + OR NEW.outcome_membership_version IS DISTINCT FROM 2 + OR NEW.outcome_membership_authority_generation IS DISTINCT FROM 1 + OR NEW.membership_authority_outbox_stream_key IS NULL + OR NEW.membership_authority_outbox_sequence IS DISTINCT FROM 1 + OR NEW.membership_authority_event_id IS NULL + OR NEW.membership_authority_event_digest IS NULL + OR NEW.membership_authority_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.join_audit_event_id IS NULL + OR NEW.join_audit_payload_digest IS NULL + OR NEW.join_audit_payload_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.join_audit_occurred_at IS NULL THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt is incomplete or noncommitting' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_tenant_membership membership + WHERE membership.id = NEW.membership_id + AND membership.account_id = NEW.account_id + AND membership.tenant_uuid = NEW.tenant_uuid + AND membership.tenant_id IS NULL + AND membership.tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND membership.lifecycle_state = 'ACTIVE' + AND membership.gameplay_admission_allowed IS TRUE + AND membership.authority_provenance = 'EXPLICIT_JOIN' + AND membership.membership_version = NEW.outcome_membership_version + AND membership.membership_authority_generation = + NEW.outcome_membership_authority_generation + ) INTO membership_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_membership_pair_authority pair + JOIN account_tenant_membership membership + ON membership.id = NEW.membership_id + WHERE pair.account_uuid = NEW.account_uuid + AND pair.tenant_uuid = NEW.tenant_uuid + AND pair.membership_exists IS TRUE + AND pair.membership_version = NEW.outcome_membership_version + AND pair.membership_authority_generation = + NEW.outcome_membership_authority_generation + AND pair.last_event_sequence = NEW.membership_authority_outbox_sequence + AND pair.last_event_id = NEW.membership_authority_event_id + AND pair.last_event_digest = NEW.membership_authority_event_digest + AND pair.last_transition_invalidated IS FALSE + AND pair.tenant_provenance_kind = membership.tenant_provenance_kind + AND pair.tenant_source_operation_id = membership.tenant_source_operation_id + AND pair.tenant_provenance_digest = membership.tenant_provenance_digest + ) INTO pair_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + JOIN account_authority_outbox_streams stream + ON stream.outbox_stream_key = event.outbox_stream_key + WHERE event.outbox_stream_key = NEW.membership_authority_outbox_stream_key + AND event.outbox_sequence = NEW.membership_authority_outbox_sequence + AND event.request_id = NEW.request_id + AND event.event_id = NEW.membership_authority_event_id + AND event.event_digest = NEW.membership_authority_event_digest + AND stream.last_sequence = NEW.membership_authority_outbox_sequence + ) INTO authority_event_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_audit_outbox audit + WHERE audit.audit_event_id = NEW.join_audit_event_id + AND audit.scope = 'tenant' + AND audit.tenant_identity_version = 2 + AND audit.tenant_id IS NULL + AND audit.tenant_uuid = NEW.tenant_uuid + AND audit.producer_service = 'account-service' + AND audit.event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' + AND audit.schema_version = 1 + AND audit.payload_digest_version = 1 + AND audit.payload_digest = NEW.join_audit_payload_digest + AND audit.occurred_at = NEW.join_audit_occurred_at + AND audit.delivery_status = 'PENDING' + AND audit.payload IS NOT NULL + AND audit.payload::JSONB ->> 'accountId' = NEW.account_uuid::TEXT + AND audit.payload::JSONB ->> 'tenantId' = NEW.tenant_uuid::TEXT + AND audit.payload::JSONB ->> 'requestId' = NEW.request_id + AND audit.payload::JSONB ->> 'worldSlug' = NEW.world_slug + AND audit.payload::JSONB ->> 'realmSlug' = NEW.realm_slug + AND audit.payload::JSONB ->> 'membershipVersion' = '2' + AND audit.payload::JSONB ->> 'membershipAuthorityGeneration' = '1' + AND audit.payload::JSONB ->> 'membershipEventStreamKey' = + NEW.membership_authority_outbox_stream_key + AND audit.payload::JSONB ->> 'membershipEventSequence' = + NEW.membership_authority_outbox_sequence::TEXT + AND audit.payload::JSONB ->> 'membershipEventId' = NEW.membership_authority_event_id + AND audit.payload::JSONB ->> 'membershipEventDigest' = + NEW.membership_authority_event_digest + AND audit.payload::JSONB ->> 'joinIntentDigest' = NEW.intent_digest + AND audit.payload::JSONB ->> 'joinRequestDigest' = NEW.request_digest + AND audit.payload::JSONB ->> 'allowPublicJoin' = 'true' + AND audit.payload::JSONB ->> 'entitlementVersion' = NEW.entitlement_version::TEXT + ) INTO audit_envelope_matches; + + IF NOT membership_matches OR NOT pair_matches OR NOT authority_event_matches + OR NOT audit_envelope_matches THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt does not match committed owner evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +/* [jooq ignore stop] */ diff --git a/services/account-service/src/main/resources/db/migration/V1037__canonical_join_existing_membership_terminal.sql b/services/account-service/src/main/resources/db/migration/V1037__canonical_join_existing_membership_terminal.sql new file mode 100644 index 0000000000..60b5dc9b61 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1037__canonical_join_existing_membership_terminal.sql @@ -0,0 +1,456 @@ +-- Extend canonical V2 terminals to the ADR 0025 existing-membership lifecycle. Applied migrations +-- and retained receipts remain immutable. ACTIVE records its exact current owner/event snapshot +-- without a new transition or audit; INACTIVE restoration records one later event and audit. +/* [jooq ignore start] */ +ALTER TABLE account_join_operations DROP CONSTRAINT account_join_committed_policy_check; +ALTER TABLE account_join_operations ADD CONSTRAINT account_join_committed_policy_check CHECK ( + status <> 'COMMITTED' OR (entitlement_version IS NOT NULL AND entitlement_version > 0 + AND allow_public_join IS NOT NULL + AND (allow_public_join IS TRUE OR (operation_representation_version = 2 AND outcome = 'ALREADY_ACTIVE')) + AND membership_id IS NOT NULL AND outcome_membership_version > 0 + AND outcome_membership_authority_generation > 0) +); + +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_operation_representation_check; + +ALTER TABLE account_join_operations ADD CONSTRAINT account_join_exact_first_transition_check CHECK ( + operation_representation_version <> 2 OR status <> 'COMMITTED' OR outcome <> 'JOINED' + OR ((membership_authority_outbox_sequence = 1 AND outcome_membership_version = 2 + AND outcome_membership_authority_generation = 1) + OR (membership_authority_outbox_sequence > 1 AND outcome_membership_version > 2)) +); + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_representation_check CHECK ( + (operation_representation_version = 1 AND scope_digest_version = 1 + AND target_class IS NULL AND account_uuid IS NULL AND tenant_uuid IS NULL + AND tenant_slug IS NULL AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL) + OR + (operation_representation_version = 2 AND scope_digest_version = 2 + AND request_id IS NOT NULL AND account_id IS NOT NULL + AND verified_caller_binding IS NOT NULL AND scope_token_hash IS NOT NULL + AND connect_scope_digest IS NOT NULL AND realm_id IS NOT NULL + AND world_slug IS NOT NULL AND realm_slug IS NOT NULL + AND playable_state_scope IS NOT NULL AND catalog_revision IS NOT NULL + AND pointer_version IS NOT NULL AND intent_digest_version = 2 + AND intent_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_authority_availability IS NOT NULL + AND last_attempt_authority_availability IS NOT NULL + AND caller_bound_authority_invalidated IS FALSE + AND btrim(request_id) <> '' AND verified_caller_binding <> '' + AND scope_token_hash ~ '^sha256:[0-9a-f]{64}$' + AND target_class = 'PUBLIC_PRODUCTION' + AND tenant_id IS NULL AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug <> '' AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND connect_scope_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING' AND outcome IS NULL AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome IN ('JOINED', 'ALREADY_ACTIVE') + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version >= 2 + AND outcome_membership_authority_generation > 0))) + ); + +ALTER TABLE account_join_operations DROP CONSTRAINT account_join_canonical_terminal_proof_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_canonical_terminal_proof_check CHECK ( + (operation_representation_version = 1 + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status IN ('PENDING', 'FAILED') + AND ((status = 'PENDING' AND outcome IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE'))) AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status = 'COMMITTED' + AND outcome IN ('JOINED', 'ALREADY_ACTIVE') + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version >= 2 + AND outcome_membership_authority_generation > 0 + AND membership_authority_outbox_stream_key IS NOT NULL + AND membership_authority_outbox_stream_key = + 'account:auth-authority:v1:membership/' || account_uuid::TEXT || '/' || tenant_uuid::TEXT + AND membership_authority_outbox_sequence IS NOT NULL + AND membership_authority_outbox_sequence > 0 + AND membership_authority_event_id IS NOT NULL + AND btrim(membership_authority_event_id) <> '' + AND membership_authority_event_digest IS NOT NULL + AND membership_authority_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((outcome = 'ALREADY_ACTIVE' AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL AND join_audit_occurred_at IS NULL) + OR (outcome = 'JOINED' AND join_audit_event_id IS NOT NULL + AND join_audit_event_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND join_audit_payload_digest IS NOT NULL + AND join_audit_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND join_audit_occurred_at IS NOT NULL))) + ); + +CREATE OR REPLACE FUNCTION guard_account_join_operation_identity() RETURNS trigger AS $$ +DECLARE + scope_source_matches BOOLEAN := FALSE; + membership_matches BOOLEAN := FALSE; + pair_matches BOOLEAN := FALSE; + authority_event_matches BOOLEAN := FALSE; + audit_envelope_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.operation_representation_version = 2 THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.operation_representation_version = 1 THEN + RETURN NEW; + END IF; + IF NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.scope_digest_version IS DISTINCT FROM 2 + OR NEW.intent_digest_version IS DISTINCT FROM 2 + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.request_digest_version IS NOT NULL OR NEW.request_digest IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN operation must start as an exact pending intent' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_connect_scope_records scope_row + WHERE scope_row.scope_token_hash = NEW.scope_token_hash + AND scope_row.scope_digest_version = 2 + AND scope_row.snapshot_digest = NEW.connect_scope_digest + AND scope_row.account_id = NEW.account_id + AND scope_row.account_uuid = NEW.account_uuid + AND scope_row.target_class = NEW.target_class + AND scope_row.tenant_id IS NULL + AND scope_row.tenant_uuid = NEW.tenant_uuid + AND scope_row.tenant_slug = NEW.tenant_slug + AND scope_row.realm_id = NEW.realm_id + AND scope_row.world_slug = NEW.world_slug + AND scope_row.realm_slug = NEW.realm_slug + AND scope_row.playable_state_namespace_id IS NULL + AND scope_row.playable_state_namespace_uuid = NEW.playable_state_namespace_uuid + AND scope_row.playable_state_scope = NEW.playable_state_scope + AND scope_row.game_instance_id IS NULL + AND scope_row.game_instance_uuid = NEW.game_instance_uuid + AND scope_row.catalog_revision = NEW.catalog_revision + AND scope_row.pointer_version = NEW.pointer_version + ) INTO scope_source_matches; + IF NOT scope_source_matches THEN + RAISE EXCEPTION 'Canonical JOIN operation has no exact persisted scope source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version = 1 THEN + IF NEW.operation_representation_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'Retained JOIN operation evidence cannot change representation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version <> 2 + OR NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.verified_caller_binding IS DISTINCT FROM OLD.verified_caller_binding + OR NEW.scope_token_hash IS DISTINCT FROM OLD.scope_token_hash + OR NEW.connect_scope_digest IS DISTINCT FROM OLD.connect_scope_digest + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_slug IS DISTINCT FROM OLD.realm_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.catalog_revision IS DISTINCT FROM OLD.catalog_revision + OR NEW.pointer_version IS DISTINCT FROM OLD.pointer_version + OR NEW.intent_digest_version IS DISTINCT FROM OLD.intent_digest_version + OR NEW.intent_digest IS DISTINCT FROM OLD.intent_digest + OR NEW.scope_digest_version IS DISTINCT FROM OLD.scope_digest_version + OR NEW.target_class IS DISTINCT FROM OLD.target_class + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_slug IS DISTINCT FROM OLD.tenant_slug + OR NEW.playable_state_namespace_uuid IS DISTINCT FROM OLD.playable_state_namespace_uuid + OR NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Canonical JOIN operation intent evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.status IN ('COMMITTED', 'FAILED') THEN + RAISE EXCEPTION 'Terminal canonical JOIN receipt is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF OLD.status IS DISTINCT FROM 'PENDING' THEN + RAISE EXCEPTION 'Canonical JOIN operation has unsupported prior status' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.request_digest IS NULL THEN + IF NEW.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.allow_public_join IS NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN policy binding is incomplete' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.status = 'FAILED' THEN + IF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Unbound failed canonical JOIN cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability NOT IN ('UNAVAILABLE', 'NOT_EVALUATED') + OR NEW.last_attempt_authority_availability IS DISTINCT FROM NEW.entitlement_authority_availability + OR NEW.last_attempt_failure_code IS NULL + OR NEW.last_attempt_failure_code NOT IN ('AUTH_UNAVAILABLE', 'ENTITLEMENT_UNAVAILABLE', 'ADMISSION_POINTER_UNAVAILABLE') THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_authority_availability IS DISTINCT FROM OLD.entitlement_authority_availability + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join THEN + RAISE EXCEPTION 'Canonical JOIN available policy evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.status = 'FAILED' THEN + IF NEW.outcome IS NULL OR NEW.outcome NOT IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Failed canonical JOIN must retain original policy and no success proof' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending canonical JOIN cannot carry terminal receipt evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' + OR NEW.outcome NOT IN ('JOINED', 'ALREADY_ACTIVE') + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR (NEW.outcome = 'JOINED' AND NEW.allow_public_join IS DISTINCT FROM TRUE) + OR NEW.allow_public_join IS NULL + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.request_digest IS NULL + OR NEW.request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_attempt_failure_code IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.membership_id IS NULL + OR NEW.outcome_membership_version IS NULL OR NEW.outcome_membership_version < 2 + OR NEW.outcome_membership_authority_generation IS NULL OR NEW.outcome_membership_authority_generation <= 0 + OR NEW.membership_authority_outbox_stream_key IS NULL + OR NEW.membership_authority_outbox_sequence IS NULL OR NEW.membership_authority_outbox_sequence <= 0 + OR NEW.membership_authority_event_id IS NULL + OR NEW.membership_authority_event_digest IS NULL + OR NEW.membership_authority_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR (NEW.outcome = 'JOINED' AND (NEW.join_audit_event_id IS NULL + OR NEW.join_audit_payload_digest IS NULL + OR NEW.join_audit_payload_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.join_audit_occurred_at IS NULL)) + OR (NEW.outcome = 'ALREADY_ACTIVE' AND (NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL OR NEW.join_audit_occurred_at IS NOT NULL)) THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt is incomplete or noncommitting' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_tenant_membership membership + WHERE membership.id = NEW.membership_id + AND membership.account_id = NEW.account_id + AND membership.tenant_uuid = NEW.tenant_uuid + AND membership.tenant_id IS NULL + AND membership.tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND membership.lifecycle_state = 'ACTIVE' + AND (NEW.outcome = 'ALREADY_ACTIVE' OR membership.gameplay_admission_allowed IS TRUE) + AND (NEW.outcome = 'ALREADY_ACTIVE' OR membership.authority_provenance = 'EXPLICIT_JOIN') + AND membership.membership_version = NEW.outcome_membership_version + AND membership.membership_authority_generation = + NEW.outcome_membership_authority_generation + ) INTO membership_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_membership_pair_authority pair + JOIN account_tenant_membership membership + ON membership.id = NEW.membership_id + WHERE pair.account_uuid = NEW.account_uuid + AND pair.tenant_uuid = NEW.tenant_uuid + AND pair.membership_exists IS TRUE + AND pair.membership_version = NEW.outcome_membership_version + AND pair.membership_authority_generation = + NEW.outcome_membership_authority_generation + AND pair.last_event_sequence = NEW.membership_authority_outbox_sequence + AND pair.last_event_id = NEW.membership_authority_event_id + AND pair.last_event_digest = NEW.membership_authority_event_digest + AND (NEW.outcome = 'ALREADY_ACTIVE' OR pair.last_transition_invalidated IS FALSE) + AND pair.tenant_provenance_kind = membership.tenant_provenance_kind + AND pair.tenant_source_operation_id = membership.tenant_source_operation_id + AND pair.tenant_provenance_digest = membership.tenant_provenance_digest + ) INTO pair_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + JOIN account_authority_outbox_streams stream + ON stream.outbox_stream_key = event.outbox_stream_key + JOIN account_tenant_membership membership ON membership.id = NEW.membership_id + JOIN account_tenant_membership_role_snapshots role_header + ON role_header.membership_id = membership.id + AND role_header.snapshot_version = membership.membership_version + WHERE event.outbox_stream_key = NEW.membership_authority_outbox_stream_key + AND event.outbox_sequence = NEW.membership_authority_outbox_sequence + AND ((NEW.outcome = 'ALREADY_ACTIVE' AND event.request_id <> NEW.request_id) + OR (NEW.outcome = 'JOINED' AND event.request_id = NEW.request_id)) + AND event.event_id = NEW.membership_authority_event_id + AND event.event_digest = NEW.membership_authority_event_digest + AND stream.last_sequence = NEW.membership_authority_outbox_sequence + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'accountId' = NEW.account_uuid::TEXT + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'tenantId' = NEW.tenant_uuid::TEXT + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'membershipLifecycleState' = 'ACTIVE' + AND convert_from(event.payload, 'UTF8')::JSONB -> 'membershipVersion' ->> NEW.tenant_uuid::TEXT = NEW.outcome_membership_version::TEXT + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'membershipAuthorityGeneration' = NEW.outcome_membership_authority_generation::TEXT + AND (convert_from(event.payload, 'UTF8')::JSONB ->> 'gameplayAdmissionAllowed')::BOOLEAN = membership.gameplay_admission_allowed + AND convert_from(event.payload, 'UTF8')::JSONB -> 'roles' = COALESCE(( + SELECT jsonb_agg(role_identifier ORDER BY convert_to(role_identifier, 'UTF8')) + FROM account_tenant_membership_role_snapshot_roles roles + WHERE roles.membership_id = membership.id AND roles.snapshot_version = membership.membership_version + ), '[]'::JSONB) + ) INTO authority_event_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_audit_outbox audit + WHERE audit.audit_event_id = NEW.join_audit_event_id + AND audit.scope = 'tenant' + AND audit.tenant_identity_version = 2 + AND audit.tenant_id IS NULL + AND audit.tenant_uuid = NEW.tenant_uuid + AND audit.producer_service = 'account-service' + AND audit.event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' + AND audit.schema_version = 1 + AND audit.payload_digest_version = 1 + AND audit.payload_digest = NEW.join_audit_payload_digest + AND audit.occurred_at = NEW.join_audit_occurred_at + AND audit.delivery_status = 'PENDING' + AND audit.payload IS NOT NULL + AND audit.payload::JSONB ->> 'accountId' = NEW.account_uuid::TEXT + AND audit.payload::JSONB ->> 'tenantId' = NEW.tenant_uuid::TEXT + AND audit.payload::JSONB ->> 'requestId' = NEW.request_id + AND audit.payload::JSONB ->> 'worldSlug' = NEW.world_slug + AND audit.payload::JSONB ->> 'realmSlug' = NEW.realm_slug + AND audit.payload::JSONB ->> 'membershipVersion' = NEW.outcome_membership_version::TEXT + AND audit.payload::JSONB ->> 'membershipAuthorityGeneration' = NEW.outcome_membership_authority_generation::TEXT + AND audit.payload::JSONB ->> 'membershipEventStreamKey' = + NEW.membership_authority_outbox_stream_key + AND audit.payload::JSONB ->> 'membershipEventSequence' = + NEW.membership_authority_outbox_sequence::TEXT + AND audit.payload::JSONB ->> 'membershipEventId' = NEW.membership_authority_event_id + AND audit.payload::JSONB ->> 'membershipEventDigest' = + NEW.membership_authority_event_digest + AND audit.payload::JSONB ->> 'joinIntentDigest' = NEW.intent_digest + AND audit.payload::JSONB ->> 'joinRequestDigest' = NEW.request_digest + AND audit.payload::JSONB ->> 'allowPublicJoin' = 'true' + AND audit.payload::JSONB ->> 'entitlementVersion' = NEW.entitlement_version::TEXT + ) INTO audit_envelope_matches; + + IF NOT membership_matches OR NOT pair_matches OR NOT authority_event_matches + OR (NEW.outcome = 'JOINED' AND NOT audit_envelope_matches) THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt does not match committed owner evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +/* [jooq ignore stop] */ diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 4745356dd3..198a024c09 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -189,8 +189,9 @@ components: type: string BootstrapRealmDto: type: object + description: Public realm selector evidence; the retained scope does not grant entry or character access. required: - [worldSlug, realmSlug, realmId, catalogRevision, playableStateNamespaceId, playableStateScope] + [worldSlug, realmSlug, realmId, tenantId, gameInstanceId, catalogRevision, playableStateNamespaceId, playableStateScope] properties: worldSlug: type: string @@ -202,9 +203,11 @@ components: displayName: type: string tenantId: - type: integer + type: string + format: uuid gameInstanceId: - type: integer + type: string + format: uuid pointerVersion: type: integer catalogRevision: @@ -217,8 +220,6 @@ components: playableStateScope: type: string enum: [PLAYABLE_STATE_SCOPE_SHARED, PLAYABLE_STATE_SCOPE_ISOLATED] - requiresCharacterSelection: - type: boolean stateScope: type: string enum: [SHARED, ISOLATED] @@ -233,13 +234,27 @@ components: description: Opaque signed scope with canonical UUID Account identity; obtain fresh scope through discovery rather than interpreting its payload. BootstrapCharacterDto: type: object + description: Persisted, non-admitting actor discovery for the current public SHARED PRESEEDED_ONLY target. + required: [characterId, characterName, level, stateScope, characterCreationPolicy] properties: characterId: type: string + format: uuid characterName: type: string + minLength: 1 + maxLength: 100 level: type: integer + format: int32 + minimum: 0 + description: Actual persisted Entity level from the same eligible actor row. + stateScope: + type: string + enum: [SHARED] + characterCreationPolicy: + type: string + enum: [PRESEEDED_ONLY] ResultStatus: type: string enum: [SUCCESS, ERROR] 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 8a1838fbec..cd88bd7679 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 @@ -7,8 +7,13 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.Callable; @@ -16,22 +21,73 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; -import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -88,9 +144,11 @@ static void configure(DynamicPropertyRegistry registry) { } @LocalServerPort private int port; + @Autowired private javax.sql.DataSource dataSource; @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired private AccountServiceImpl canonicalFacade; @Autowired private SessionService realAccountSessions; @Autowired private HttpAuthProperties httpAuthProperties; @Autowired private ObjectProvider httpJwtAuthInterceptorProvider; @@ -396,6 +454,1785 @@ private List emailVerificationState(EmailVerificationFixture fixture) { private record EmailVerificationFixture(long accountId, String token) {} + @Test + void publicJoinBrowserAndDirectScopesUseActualUuidIntentMembershipEventAndAuditOwners() + throws Exception { + var f = publicJoinFixture(false); + var worlds = f.service.listBootstrapWorlds(f.bootstrap); + assertThat(worlds).extracting(value -> value.worldSlug()).containsExactly(f.target.worldSlug()); + var browser = f.browserScope(); + var direct = f.directScope(); + for (String token : List.of(browser, direct)) { + var claims = f.jwt.parseToken(token).getPayload(); + assertThat(claims.getSubject()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(claims.get("tenantId")).isEqualTo(f.tenantId.toString()); + assertThat(claims.get("gameInstanceId")) + .isEqualTo(f.target.canonicalGameInstanceId().toString()); + var retained = + f.in( + () -> + f.scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(token)) + .orElseThrow()); + assertThat(retained.privateAccountId()).isEqualTo(f.account.getId()); + assertThat(retained.scopeDigestVersion()).isEqualTo(2); + assertThat(retained.tenantUuid()).isEqualTo(f.tenantId); + assertThat(f.in(() -> f.scopes.find(token))).isEmpty(); + } + for (String token : List.of(browser, direct)) { + assertThatThrownBy( + () -> + f.service.issueConnectToken( + f.bootstrap, + new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( + token, "held-issuer"))) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + } + String request = UUID.randomUUID().toString(); + var first = f.join(browser, request); + assertThat(first.success()).isTrue(); + assertThat(first.accountId()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(f.tenantId); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.membershipAuthorityGeneration()).isEqualTo(1L); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.times(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + var committed = f.state(request); + var replay = f.join(browser, request); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + var active = f.directJoin(direct, UUID.randomUUID().toString()); + assertThat(active.success()).isTrue(); + assertThat(active.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(active.membershipVersion()).isEqualTo(first.membershipVersion()); + assertThat(active.membershipAuthorityGeneration()) + .isEqualTo(first.membershipAuthorityGeneration()); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinPaidOwnerUsesRealProvisioningCurrentRowFenceAndSealedStripeObservation() { + var f = publicJoinFixture(true); + String token = f.browserScope(); + int reads = f.paid.transport().reads(); + String request = UUID.randomUUID().toString(); + var first = f.join(token, request); + assertThat(first.success()).isTrue(); + assertThat(f.paid.transport().reads()).isGreaterThan(reads); + f.assertTransitionCount(1L); + assertThat(f.operation(request).operationRepresentationVersion()).isEqualTo(2); + assertThat(f.operation(request).entitlementVersion()).isPositive(); + assertThat(f.operation(request).terminalProof().entitlementVersion()) + .isEqualTo(f.operation(request).entitlementVersion()); + } + + @Test + void publicJoinStrictPublishedWorldSourceOutageCannotCommitFromResolverOnlyEvidence() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + org.mockito.Mockito.when( + f.targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenThrow( + new IllegalStateException("controlled strict published/World ACTIVE source outage")); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).lastAttemptFailureCode()) + .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + } + + @Test + void publicJoinFailureBeforeCommitRollsBackMembershipPairEventAuditAndTerminalReceipt() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var failed = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + var result = invocation.callRealMethod(); + if (failed.compareAndSet(false, true)) + throw new IllegalStateException("controlled terminal rollback"); + return result; + }) + .when(f.operations) + .commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(request), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).terminalProof()).isNull(); + assertThat(f.operation(request).requestDigest()).isNull(); + f.assertTransitionCount(0L); + assertThat(f.membershipCount()).isZero(); + String intent = f.operation(request).intentDigest(); + assertThat(f.join(token, request).success()).isTrue(); + assertThat(f.operation(request).intentDigest()).isEqualTo(intent); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinLostCommitAcknowledgementReplaysTheCompleteCommittedOriginal() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var lost = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + var result = invocation.callRealMethod(); + if (lost.compareAndSet(false, true)) { + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCommit() { + throw new IllegalStateException( + "controlled lost commit acknowledgement"); + } + }); + } + return result; + }) + .when(f.operations) + .commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(request), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + assertThat(f.operation(request).status()).isEqualTo("COMMITTED"); + var committed = f.state(request); + var replay = f.join(token, request); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinActualSqlAbortAtFinalEntitlementReadRetainsIntentAndRecoversOnce() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var abort = new AtomicBoolean(true); + org.mockito.Mockito.doAnswer( + invocation -> { + if (abort.compareAndSet(true, false)) { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + dsl.fetch("SELECT 1 / 0"); + } + return invocation.callRealMethod(); + }) + .when(f.demos) + .revalidate(org.mockito.ArgumentMatchers.any()); + var failure = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, () -> f.join(token, request)); + assertThat(failure.getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(sqlState(failure)).isEqualTo("22012"); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.operation(request).requestDigest()).isNull(); + f.assertTransitionCount(0L); + String intent = f.operation(request).intentDigest(); + assertThat(f.join(token, request).success()).isTrue(); + assertThat(f.operation(request).intentDigest()).isEqualTo(intent); + f.assertTransitionCount(1L); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinUnavailableCanonicalSourceRetainsOriginalIntentAndRecovers(boolean sourceRead) { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var outage = new AtomicBoolean(true); + if (sourceRead) { + org.mockito.Mockito.doAnswer( + invocation -> { + if (outage.get()) + throw new org.springframework.dao.DataAccessResourceFailureException( + "source unavailable"); + return invocation.callRealMethod(); + }) + .when(f.sources) + .readCurrentSourceSelection(f.tenantId); + } else { + org.mockito.Mockito.doAnswer( + invocation -> { + if (outage.get()) + throw new org.springframework.dao.DataAccessResourceFailureException( + "demo unavailable"); + return invocation.callRealMethod(); + }) + .when(f.demos) + .readCurrent(f.tenantId); + } + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + var pending = f.operation(request); + assertThat(pending.status()).isEqualTo("PENDING"); + assertThat(pending.requestDigest()).isNull(); + assertThat(pending.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + outage.set(false); + assertThat(f.join(token, request).success()).isTrue(); + assertThat(f.operation(request).intentDigest()).isEqualTo(pending.intentDigest()); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinLostResponseThenExpiredScopePreservesCompleteCommittedOriginal() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + assertThat(f.join(token, request).success()).isTrue(); + var committed = f.state(request); + f.clock.offset = Duration.ofMinutes(3); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinExpiredPendingScopePreservesIntentAndCannotCommitMembership() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled source outage")) + .when(f.demos) + .readCurrent(f.tenantId); + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + var pending = f.state(request); + f.clock.offset = Duration.ofMinutes(3); + org.mockito.Mockito.doCallRealMethod().when(f.demos).readCurrent(f.tenantId); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(request)).isEqualTo(pending); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + } + + @Test + void publicJoinChangedCallerOrScopeCannotReplaceOriginalTerminalBytes() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + assertThat(f.join(token, request).success()).isTrue(); + var committed = f.state(request); + String different = f.browserScope(); + assertThatThrownBy(() -> f.join(different, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinFreshClosedPolicyPersistsDenialWithoutMembershipOrTransition() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + f.policy(false, true); + String request = UUID.randomUUID().toString(); + var denied = f.join(token, request); + assertThat(denied.success()).isFalse(); + assertThat(denied.outcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(f.operation(request).status()).isEqualTo("FAILED"); + assertThat(f.operation(request).allowPublicJoin()).isFalse(); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + var original = f.state(request); + assertThat(f.join(token, request).replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(original); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinTerminalEntitlementOutagePreservesOriginalBytesAndRecovers(boolean paid) { + var f = publicJoinFixture(paid); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var original = f.join(token, request); + assertThat(original.success()).isTrue(); + var committed = f.state(request); + if (paid) { + // A complete but contradictory provider object cannot be used as cached current authority. + f.paid.providerStatus("unpaid"); + } else { + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled current demo outage")) + .when(f.demos) + .readCurrent(f.tenantId); + } + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + if (paid) f.paid.providerStatus("active"); + else org.mockito.Mockito.doCallRealMethod().when(f.demos).readCurrent(f.tenantId); + var recovered = f.join(token, request); + assertThat(recovered.success()).isTrue(); + assertThat(recovered.replayed()).isTrue(); + assertThat(recovered.membershipId()).isEqualTo(original.membershipId()); + assertThat(recovered.membershipVersion()).isEqualTo(original.membershipVersion()); + assertThat(recovered.membershipAuthorityGeneration()) + .isEqualTo(original.membershipAuthorityGeneration()); + assertThat(f.state(request)).isEqualTo(committed); + } + + @Test + void publicJoinChangedAvailablePolicyCannotRebindTheOriginalTerminalReceipt() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + assertThat(f.join(token, request).success()).isTrue(); + var committed = f.state(request); + // The new current version is still open; immutable request/policy evidence must still conflict. + f.policy(true, true); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinRestoresControlledInactiveSnapshotOnceAndPreservesAuthorityGeneration() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledInactiveSnapshot(); + String request = UUID.randomUUID().toString(); + var restored = f.join(token, request); + assertThat(restored.success()).isTrue(); + assertThat(restored.outcomeCode()).isEqualTo("JOINED"); + assertThat(restored.membershipVersion()).isEqualTo(4L); + assertThat(restored.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(f.membershipCount()).isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + f.stream())) + .isEqualTo(3L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + f.tenantId)) + .isEqualTo(2L); + var committed = f.state(request); + assertThat(f.join(token, request).replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(committed); + } + + @Test + void publicJoinActiveControlOnlyMemberReturnsCurrentSnapshotWithoutGrantingGameplay() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledSnapshot("ACTIVE", false, List.of("moderator")); + f.policy(false, true); + String request = UUID.randomUUID().toString(); + var result = f.join(token, request); + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.membershipVersion()).isEqualTo(3L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(result.gameplayAdmissionAllowed()).isFalse(); + assertThat(f.currentRoles()).containsExactly("moderator"); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + f.stream())) + .isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + f.tenantId)) + .isEqualTo(1L); + var committed = f.state(request); + var replay = f.join(token, request); + assertThat(replay.success()).isTrue(); + assertThat(replay.gameplayAdmissionAllowed()).isFalse(); + assertThat(replay.replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(committed); + assertThat(f.currentRoles()).containsExactly("moderator"); + } + + @Test + void publicJoinAnotherAuthenticatedAccountCannotConsumeTheOriginalScopeOrCreateIntent() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String suffix = UUID.randomUUID().toString(); + var other = + accountService.createAccount( + new CreateAccountRequest( + "other-facade-" + suffix, + "other-facade-" + suffix + "@example.test", + "password123")); + Account owner = f.accounts.findByAccountUuid(UUID.fromString(other.id())).orElseThrow(); + String bootstrap = + f.jwt.generateToken( + other.id(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + other.id(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(f.sessions.isAccountSessionActive(owner.getId(), bootstrap)) + .thenReturn(true); + String request = UUID.randomUUID().toString(); + assertThatThrownBy( + () -> + f.service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(token, request))) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.in(() -> f.operations.findCanonicalEvidenceByRequestId(request))).isEmpty(); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void bootstrapCharactersUsesActualAccountAuthorityAndPreservesControlledEntityNamesAndLevels( + boolean paid) { + var f = publicJoinFixture(paid); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + UUID ada = UUID.randomUUID(), zed = UUID.randomUUID(); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(zed, "Zed", 37), + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(ada, "Ada", 12)); + }); + var before = f.state(join); + int providerReads = paid ? f.paid.transport().reads() : 0; + var actors = f.characters(token); + assertThat(actors).extracting(value -> value.characterName()).containsExactly("Ada", "Zed"); + assertThat(actors) + .extracting(value -> value.characterId()) + .containsExactly(ada.toString(), zed.toString()); + assertThat(actors).extracting(value -> value.level()).containsExactly(12, 37); + assertThat(actors) + .allSatisfy( + actor -> { + assertThat(actor.stateScope()).isEqualTo("SHARED"); + assertThat(actor.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); + }); + var selected = + org.mockito.ArgumentCaptor.forClass( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + selected.capture()); + assertThat(selected.getValue().selector().canonicalAccountUuid()) + .isEqualTo(f.account.getAccountUuid()); + assertThat(selected.getValue().selector().canonicalTenantUuid()).isEqualTo(f.tenantId); + assertThat(selected.getValue().selector().realmUuid()).isEqualTo(f.target.realmId()); + assertThat(selected.getValue().selector().playableStateNamespaceUuid()) + .isEqualTo(f.target.playableStateNamespaceId()); + assertThat(selected.getValue().selector().canonicalGameInstanceUuid()) + .isEqualTo(f.target.canonicalGameInstanceId()); + assertThat(selected.getValue().selector().canonicalVersionUuid()) + .isEqualTo(f.target.canonicalVersionId()); + assertThat(selected.getValue().selector().expectedCatalogRevision()) + .isEqualTo(f.target.catalogRevision()); + assertThat(selected.getValue().selector().expectedPointerVersion()) + .isEqualTo(f.target.pointerVersion()); + assertThat(selected.getValue().selector().expectedActiveWorldEpoch()) + .isEqualTo(f.target.activeWorldEpoch()); + if (paid) assertThat(f.paid.transport().reads()).isGreaterThanOrEqualTo(providerReads + 2); + assertThat(f.state(join)).isEqualTo(before); + f.assertTransitionCount(1L); + } + + @Test + void bootstrapCharactersValidEmptyResultStillRequiresSuccessfulEntityDiscovery() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + assertThat(f.characters(token)).isEmpty(); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any()); + f.assertTransitionCount(1L); + } + + @Test + void + bootstrapCharactersSameAccountAndDuplicateWorldRealmNamesRemainBoundToExactTenantAndTarget() { + var first = publicJoinFixture(false); + var second = new CanonicalPublicJoinFixture(false, first.account); + String firstScope = first.browserScope(), secondScope = second.browserScope(); + assertThat(first.target.worldSlug()).isEqualTo(second.target.worldSlug()); + assertThat(first.target.realmSlug()).isEqualTo(second.target.realmSlug()); + assertThat(first.tenantId).isNotEqualTo(second.tenantId); + assertThat(first.join(firstScope, UUID.randomUUID().toString()).success()).isTrue(); + assertThat(second.join(secondScope, UUID.randomUUID().toString()).success()).isTrue(); + UUID firstActor = UUID.randomUUID(), secondActor = UUID.randomUUID(); + org.mockito.Mockito.when( + first.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(first.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(firstActor, "First tenant actor", 9))); + org.mockito.Mockito.when( + second.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(second.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(secondActor, "Second tenant actor", 21))); + assertThat(first.characters(firstScope)) + .extracting(value -> value.characterId()) + .containsExactly(firstActor.toString()); + assertThat(second.characters(secondScope)) + .extracting(value -> value.characterId()) + .containsExactly(secondActor.toString()); + var selected = + org.mockito.ArgumentCaptor.forClass( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.verify(first.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(first.account.getAccountUuid()), + selected.capture()); + assertThat(selected.getValue().selector().canonicalTenantUuid()).isEqualTo(first.tenantId); + org.mockito.Mockito.verify(second.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(second.account.getAccountUuid()), + selected.capture()); + assertThat(selected.getValue().selector().canonicalTenantUuid()).isEqualTo(second.tenantId); + assertThat(selected.getValue().selector().realmUuid()).isEqualTo(second.target.realmId()); + assertThat(selected.getValue().selector().playableStateNamespaceUuid()) + .isEqualTo(second.target.playableStateNamespaceId()); + assertThat(selected.getValue().selector().canonicalGameInstanceUuid()) + .isEqualTo(second.target.canonicalGameInstanceId()); + } + + @Test + void bootstrapCharactersAnotherAuthenticatedAccountCannotConsumeTheSelectedScope() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + String suffix = UUID.randomUUID().toString(); + var other = + accountService.createAccount( + new CreateAccountRequest( + "other-roster-" + suffix, + "other-roster-" + suffix + "@example.test", + "password123")); + Account owner = f.accounts.findByAccountUuid(UUID.fromString(other.id())).orElseThrow(); + String bootstrap = + f.jwt.generateToken( + other.id(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + other.id(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(f.sessions.isAccountSessionActive(owner.getId(), bootstrap)) + .thenReturn(true); + assertThatThrownBy( + () -> + f.service.listBootstrapCharacters( + bootstrap, f.target.worldSlug(), f.target.realmSlug(), token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + f.assertTransitionCount(1L); + } + + @Test + void bootstrapCharactersMissingAndControlledInactiveMembersRequireJoinWithoutEntityDisclosure() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("JOIN_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledInactiveSnapshot(); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("JOIN_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + } + + @Test + void bootstrapCharactersClosedPolicyAndControlOnlyMembershipCannotBecomeAnEmptySuccess() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + f.policy(false, true); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + f.policy(true, true); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledSnapshot("ACTIVE", false, List.of("moderator")); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(f.currentRoles()).containsExactly("moderator"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + } + + @Test + void bootstrapCharactersRechecksActualMembershipSnapshotAfterEntityDiscovery() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + f.seedControlledInactiveSnapshot(); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 19)); + }); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + assertThat(f.operation(join).status()).isEqualTo("COMMITTED"); + assertThat(f.operation(join).membershipVersion()).isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT lifecycle_state FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + f.account.getId(), + f.tenantId)) + .isEqualTo("INACTIVE"); + assertThat( + dsl.fetchValue( + "SELECT membership_version FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + f.account.getId(), + f.tenantId)) + .isEqualTo(3L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + f.stream())) + .isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + f.tenantId)) + .isEqualTo(1L); + } + + @Test + void bootstrapCharactersFinalEntitlementOutageDiscardsEntityResultAndPreservesAccountState() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + var before = f.state(join); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled late demo currentness outage")) + .when(f.demos) + .revalidate(org.mockito.ArgumentMatchers.any()); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 31)); + }); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.state(join)).isEqualTo(before); + f.assertTransitionCount(1L); + } + + @Test + void bootstrapCharactersEntityFailureAndExpiredScopeNeverReturnAnEmptySuccess() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + var before = f.state(join); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenThrow(new IllegalStateException("controlled Entity discovery failure")); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + f.clock.offset = Duration.ofMinutes(3); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(join)).isEqualTo(before); + f.assertTransitionCount(1L); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sql) return sql.getSQLState(); + } + return null; + } + + private CanonicalPublicJoinFixture publicJoinFixture(boolean paid) { + return new CanonicalPublicJoinFixture(paid); + } + + /** + * Actual Account SQL/JWT/intent/subscription/member/event/audit composition. GS + * resolver/published-source/World ACTIVE responses and caller registry inputs are controlled (the + * strict source decoder and remote freshness are not qualified); this does not qualify PKI, + * issuer custody or runtime registration. + */ + private final class CanonicalPublicJoinFixture { + private final String namespace; + private final AccountRepository accounts = new AccountRepository(dsl); + private final AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + private final AccountAuthorityOutboxRepository outbox = + new AccountAuthorityOutboxRepository(dsl); + private final AccountAuthoritySourceEvidenceRepository evidence = + new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + private final AccountMembershipPairAuthorityRepository pairs = + new AccountMembershipPairAuthorityRepository(dsl); + private final AccountTenantMembershipRoleSnapshotRepository roles = + new AccountTenantMembershipRoleSnapshotRepository(dsl); + private final AccountAuditOutboxRepository audits = new AccountAuditOutboxRepository(dsl); + private final FreshTenantIdentityAssociationRepository tenants; + private final AccountTenantMembershipRepository members; + private final AccountTenantAuthorityEventRepository sources; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountConnectScopeRepository scopes; + private final AccountJoinOperationRepository operations; + private final AccountCanonicalFirstJoinTerminalCoordinator terminal; + private final integration.net.firedevops.firemud.accountservice.repository + .CanonicalHostingSubscriptionTestFixture.Fixture + paid; + private final AccountHostingSubscriptionLifecycleRepository hosting; + private final StripeHostingSubscriptionObserver observer; + private final FreshTenantCreationEvidence source; + private final UUID tenantId; + private final Account account; + private final FixtureClock clock; + private final TransactionTemplate transaction = new TransactionTemplate(transactionManager); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final SessionService sessions = org.mockito.Mockito.mock(SessionService.class); + private final net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + roster = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .class); + private final JwtUtil jwt = + new JwtUtil("controlled-public-facade-fixture-key-01234567890123456789", 300000L); + private final String bootstrap; + private final AccountServiceImpl service; + private final Target target; + + private CanonicalPublicJoinFixture(boolean usePaid) { + this(usePaid, null); + } + + private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { + namespace = usePaid ? "prod" : "test"; + transaction.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE); + tenants = new FreshTenantIdentityAssociationRepository(dsl, namespace); + members = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + sources = + org.mockito.Mockito.spy( + new AccountTenantAuthorityEventRepository( + dsl, outbox, billing, tenants, generations)); + demos = + org.mockito.Mockito.spy( + new AccountDemoTenantEntitlementRepository( + dsl, tenants, generations, billing, sources)); + scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class), + namespace), + tenants); + operations = org.mockito.Mockito.spy(new AccountJoinOperationRepository(dsl, scopes)); + var producer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + members, + roles, + generations, + outbox, + evidence, + sources, + demos); + terminal = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, operations, members, roles, outbox, pairs, audits, producer); + if (usePaid) { + paid = + integration.net.firedevops.firemud.accountservice.repository + .CanonicalHostingSubscriptionTestFixture.create(dataSource); + var claim = + paid.service() + .claimProvisioning(paid.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + assertThat( + paid.service() + .reconcile( + UUID.randomUUID(), + paid.creation().requestId(), + claim.subscriptionRowVersion(), + paid.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + hosting = paid.lifecycleRepository(); + observer = paid.observer(); + tenantId = paid.tenantId(); + source = in(() -> tenants.read(tenantId).orElseThrow()); + clock = new FixtureClock(paid.clock()); + } else { + paid = null; + hosting = org.mockito.Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class); + observer = org.mockito.Mockito.mock(StripeHostingSubscriptionObserver.class); + tenantId = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String key = "f-" + tenantId.toString().replace("-", ""); + String digest = + GameTenantCreationDigest.requestDigest(namespace, request, key, "Facade fixture", null); + source = + new FreshTenantCreationEvidence( + 1, + namespace, + request, + operation, + digest, + tenantId, + 100000000L + Integer.toUnsignedLong(key.hashCode()), + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + request, + operation, + digest, + tenantId, + 100000000L + Integer.toUnsignedLong(key.hashCode()), + key, + "NEW_GAME_ROW")); + clock = new FixtureClock(Clock.systemUTC()); + in( + () -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(tenantId); + return null; + }); + policy(true, true); + } + String suffix = UUID.randomUUID().toString(); + if (existingAccount == null) { + var created = + accountService.createAccount( + new CreateAccountRequest( + "facade-" + suffix, "facade-" + suffix + "@example.test", "password123")); + account = accounts.findByAccountUuid(UUID.fromString(created.id())).orElseThrow(); + } else { + account = accounts.findByAccountUuid(existingAccount.getAccountUuid()).orElseThrow(); + } + in( + () -> { + evidence.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + return null; + }); + if (paid != null) { + // The SQL lifecycle owner evaluates at microsecond precision; its SDK input must use the + // same controlled instant rather than appear nanoseconds later than the evaluation. + Instant browserTime = + Instant.now().plusSeconds(1).truncatedTo(java.time.temporal.ChronoUnit.MICROS); + if (paid.clock().instant().isBefore(browserTime)) { + paid.clock().advance(Duration.between(paid.clock().instant(), browserTime)); + } + } + target = target(); + org.mockito.Mockito.when( + targets.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), namespace); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target))); + }); + org.mockito.Mockito.when( + targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target)); + }); + // The transport boundary is controlled. Actual Account owners must still request this strict + // published-source/World ACTIVE result; the resolver response alone cannot authorize JOIN. + org.mockito.Mockito.when( + targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + var published = + org.mockito.Mockito.mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + org.mockito.Mockito.when(published.selector()).thenReturn(strict); + org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + org.mockito.Mockito.when(sourceEvidence.request()).thenReturn(strict); + org.mockito.Mockito.when(sourceEvidence.admissionPointerSnapshotDigest()) + .thenReturn(target.admissionPointerSnapshotDigest()); + // Controlled remote policy capture; the Account integration test does not qualify + // its decoder. + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication + .PublishedRealmEntryPolicySetEvidence.class); + org.mockito.Mockito.when(policies.canonicalBytes()) + .thenReturn( + ("controlled-policy-set-" + tenantId).getBytes(StandardCharsets.UTF_8)); + org.mockito.Mockito.when(sourceEvidence.publishedPolicySetEvidence()) + .thenReturn(policies); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + org.mockito.Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); + org.mockito.Mockito.when(world.lifecycleEpoch()) + .thenReturn(target.activeWorldEpoch()); + org.mockito.Mockito.when(world.rowVersion()).thenReturn(1L); + org.mockito.Mockito.when(published.sourceEvidence()).thenReturn(sourceEvidence); + org.mockito.Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); + var properties = new AccountTokenProperties(); + properties.setConnectScopeExpirationMs(120000L); + bootstrap = + jwt.generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(sessions.isAccountSessionActive(account.getId(), bootstrap)) + .thenReturn(true); + var caller = new AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions); + var entitlement = + new AccountPublicBootstrapEntitlementOwner( + sources, + new AccountHostingSubscriptionLifecycleService(hosting, observer, transactionManager), + demos, + transactionManager, + clock); + service = + new AccountServiceImpl( + accounts, + generations, + evidence, + outbox, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + audits, + operations, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountEmailLoginChallengeRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository + .class), + members, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + new net.firedevops.firemud.accountservice.config.MailProperties(), + properties, + new net.firedevops.firemud.common.security.JwtAuthProperties(), + jwt, + sessions, + transactionManager); + service.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner(caller, targets, entitlement, clock)); + service.setCanonicalPublicRealmScopeOwner( + new AccountCanonicalPublicRealmScopeOwner( + caller, + targets, + entitlement, + accounts, + members, + tenants, + sources, + scopes, + jwt, + properties, + clock, + transactionManager, + namespace)); + service.setAccountBootstrapRosterReadClient(roster); + org.mockito.Mockito.when( + roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + return List.of(); + }); + service.setCanonicalScopeConsumers( + new AccountCanonicalConnectScopeReader(jwt, scopes, transactionManager, clock), + targets, + sources, + demos, + hosting, + observer, + terminal, + namespace, + clock); + } + + private void policy(boolean join, boolean gameplay) { + in( + () -> { + DemoTenantEntitlementSnapshot previous; + try { + previous = demos.readCurrent(tenantId); + } catch ( + net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException + missing) { + if (missing.code() + != net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException + .Code.ENTITLEMENT_UNAVAILABLE) throw missing; + previous = null; + } + return demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + source.creationRequestId(), + source.requestDigest(), + previous == null ? null : previous.entitlementVersion(), + previous == null ? null : previous.tenantAuthorityGeneration(), + previous == null ? null : previous.tenantAuthoritySourceVersion(), + gameplay, + join, + gameplay, + gameplay, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)), + source); + }); + } + + private Target target() { + UUID realm = UUID.randomUUID(), + state = UUID.randomUUID(), + instance = UUID.randomUUID(), + version = UUID.randomUUID(); + String digest = "a".repeat(64), initial = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request( + namespace, + tenantId, + "world", + realm, + state, + "SHARED", + instance, + version, + 1L, + initial, + digest, + net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold + .InitialAdmissionOrigin.NO_PRIOR_POINTER, + 23L, + null); + var hold = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, UUID.randomUUID(), UUID.randomUUID()); + return new Target( + namespace, + "tenant", + tenantId, + "world", + "World", + realm, + "production", + "Production", + 11L, + 44L, + state, + "SHARED", + instance, + version, + 1L, + 23L, + 17L, + digest, + 1L, + initial, + digest, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + 1L, + "sha256:" + digest, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, + false, + clock.instant(), + "PRESEEDED_ONLY"); + } + + private String browserScope() { + return service.listBootstrapRealms(bootstrap, target.worldSlug()).getFirst().connectScopeId(); + } + + private List characters( + String token) { + return service.listBootstrapCharacters( + bootstrap, target.worldSlug(), target.realmSlug(), token); + } + + private DirectTextCallerContext directCaller(String request) { + return new DirectTextCallerContext( + account.getAccountUuid(), + tenantId, + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + UUID.nameUUIDFromBytes( + ("session-" + account.getAccountUuid()).getBytes(StandardCharsets.UTF_8)) + .toString(), + request); + } + + private String directScope() throws Exception { + String request = UUID.randomUUID().toString(); + return peer() + .call( + () -> + service + .issueDirectTextConnectScope( + directCaller(request), + new DirectTextJoinTarget( + tenantId, + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion())) + .connectScopeId()); + } + + private JoinPublicProductionResult directJoin(String token, String request) throws Exception { + return peer() + .call( + () -> + service.joinPublicProductionFromGameSession( + directCaller(request), new JoinPublicProductionRequest(token, request))); + } + + private io.grpc.Context peer() { + return io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", + namespace, + "game-session-service")); + } + + private JoinPublicProductionResult join(String token, String request) { + return service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(token, request)); + } + + private AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation( + String request) { + return in(() -> operations.findCanonicalEvidenceForUpdateByRequestId(request).orElseThrow()); + } + + /** + * Controlled prior lifecycle event; this does not claim a production leave/suspension owner. + */ + private void seedControlledInactiveSnapshot() { + seedControlledSnapshot("INACTIVE", false, List.of("player")); + } + + @SuppressWarnings("unchecked") + private void seedControlledSnapshot(String lifecycle, boolean gameplay, List roleSet) { + TransactionTemplate history = new TransactionTemplate(transactionManager); + history.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + history.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + history.execute( + status -> { + operations.lockAccount(account.getId()); + var member = + members + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var generation = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + var beforeSource = + evidence.readCurrentIssuerAccountSources( + "firemud-account-service", account.getAccountUuid()); + + // Closed receipt/source-change mechanics supply the one shared Account fence advance. + // This remains controlled historical input, not a registered security or leave + // producer. + var currentSource = advanceControlledClosedAccountSource(beforeSource); + if (currentSource.account().generation() != beforeSource.account().generation() + 1L + || currentSource.account().sourceVersion() + != beforeSource.account().sourceVersion() + 1L + || currentSource.account().checkpoint().sequence() + != beforeSource.account().checkpoint().sequence() + 1L + || currentSource.issuanceFence().value() != generation.issuanceFence().value() + 1L + || currentSource.issuanceFence().sourceVersion() + != generation.issuanceFence().sourceVersion() + 1L) { + throw new IllegalStateException( + "Controlled Account source/fence did not advance once"); + } + int advanced = + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE scope_kind = 'MEMBERSHIP' AND issuer_id IS NULL " + + "AND account_uuid = ? AND tenant_uuid = ? AND generation = ? AND source_version = ?", + account.getAccountUuid(), + tenantId, + generation.generation(), + generation.sourceVersion()); + if (advanced != 1) { + throw new IllegalStateException( + "Controlled membership authority CAS did not advance once"); + } + var authority = + generations.readCompositeSnapshot( + "firemud-account-service", + account.getAccountUuid(), + List.of(tenantId), + List.of(tenantId)); + var next = authority.memberships().getFirst(); + if (next.generation() != generation.generation() + 1L + || next.sourceVersion() != generation.sourceVersion() + 1L + || !next.issuanceFence().equals(currentSource.issuanceFence()) + || !authority.issuanceFence().equals(currentSource.issuanceFence())) { + throw new IllegalStateException( + "Controlled membership differs from the actual Account fence"); + } + var tenantSource = sources.readCurrentSourceSelection(tenantId).checkpoint(); + var prior = pairs.readForUpdate(account.getAccountUuid(), tenantId).orElseThrow(); + var previous = outbox.findEvent(stream(), prior.eventSequence()).orElseThrow(); + Map event = + JsonMapper.builder() + .build() + .readValue(new String(previous.payload(), StandardCharsets.UTF_8), Map.class); + event.remove("eventDigest"); + String leave = "controlled-inactive-" + UUID.randomUUID(); + event.put("eventId", UUID.randomUUID().toString()); + event.put("requestId", leave); + event.put("outboxSequence", "2"); + event.put("membershipLifecycleState", lifecycle); + event.put("roles", roleSet); + event.put("membershipVersion", Map.of(tenantId.toString(), "3")); + event.put("membershipAuthorityGeneration", Long.toString(next.generation())); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); + tuple.put( + "accountAuthorityGeneration", Long.toString(authority.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of( + tenantId.toString(), + Long.toString(authority.tenants().getFirst().generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(next.generation()))); + tuple.put("privateRealmGrantVersions", List.of()); + currentSource + .account() + .accountSecurityCutoff() + .ifPresent( + cutoff -> + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenantSource.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.toString(tenantSource.tenantBillingSequence()), + "outboxStreamKey", tenantSource.outboxStreamKey(), + "outboxSequence", Long.toString(tenantSource.outboxSequence())))); + event.put("authorityTuple", tuple); + event.put("issuanceFence", Long.toString(authority.issuanceFence().value())); + event.put("gameplayAdmissionAllowed", gameplay); + event.put("callerBoundAuthorityInvalidated", true); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + var appended = + outbox.append( + stream(), + leave, + sequence -> { + if (sequence != 2L) + throw new IllegalStateException("Controlled prior event sequence changed"); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = ?, membership_version = 3, membership_authority_generation = 2 WHERE id = ?", + lifecycle, + gameplay, + member.getId()); + var inactive = + members + .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var provenance = + new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + roles.replaceCanonical( + inactive, account.getAccountUuid(), tenantId, provenance, 3L, roleSet); + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = 3, membership_authority_generation = 2, last_event_sequence = 2, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE WHERE account_uuid = ? AND tenant_uuid = ?", + appended.eventId(), + appended.eventDigest(), + account.getAccountUuid(), + tenantId); + return null; + }); + } + + /** + * Completes one controlled closed security-state receipt in the caller's history transaction. + */ + private AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot + advanceControlledClosedAccountSource( + AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot beforeSource) { + Account current = accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); + var sourceState = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.account( + account.getAccountUuid())); + var roleSource = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ? FOR SHARE", + account.getAccountUuid())); + long roleVersion = roleSource.get("global_role_source_version", Long.class); + var beforeState = + new AccountState( + current.isEmailVerified(), + AccountLoginAuthModes.read(current.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleSource.get("global_roles", String[].class)) + .sorted() + .toList(), + current.getLifecycleState().name()); + var afterState = + new AccountState( + !beforeState.emailVerified(), + beforeState.loginAuthModes(), + beforeState.globalRoles(), + beforeState.lifecycleState()); + UUID requestId = UUID.randomUUID(); + // These bytes are retained fixture correlation, not authenticated caller authorization. + byte[] correlation = + ("{\"actorAccountUuid\":\"" + + account.getAccountUuid() + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + requestId + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + var request = + new AccountSecurityStateMutationRequest( + requestId, + account.getAccountUuid(), + correlation, + sourceState.generation(), + sourceState.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(beforeState, afterState), + afterState); + var checkpoint = beforeSource.account().checkpoint(); + byte[] checkpointPayload = + checkpoint.sequence() == 0L + ? new byte[0] + : outbox + .findEvent(checkpoint.outboxStreamKey(), checkpoint.sequence()) + .orElseThrow() + .payload(); + var draft = + new Capture( + current.getId(), + current.getAccountUuidProvenance(), + beforeState, + sourceState, + checkpoint.sequence(), + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(sourceState.generation()), + Long.toString(sourceState.sourceVersion()), + checkpoint.outboxStreamKey(), + Long.toString(checkpoint.sequence()), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + beforeState, + sourceState, + checkpoint.sequence(), + checkpointPayload, + roleVersion, + change); + var fences = new DraftAuthorizationFenceRepository(dsl); + var security = new AccountSecurityStateOperationRepository(dsl); + if (!fences.requestSourceChange(change) + || !security.claim(request, capture).claimed() + || !fences.sourceMutationPermitted(change)) { + throw new IllegalStateException( + "Controlled closed source change is not exclusively settled"); + } + var advanced = + evidence.prepareClosedAccountAdvance(account.getAccountUuid(), beforeSource.account()); + int changed = + dsl.execute( + "UPDATE accounts SET email_verified = ? WHERE account_uuid = ? AND email_verified = ?", + afterState.emailVerified(), + account.getAccountUuid(), + beforeState.emailVerified()); + if (changed != 1) { + throw new IllegalStateException("Controlled closed Account state CAS did not change once"); + } + var event = + outbox.append( + checkpoint.outboxStreamKey(), + requestId.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + requestId, + account.getAccountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + afterState)); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + var completed = security.complete(request, event, advanced, roleVersion); + assertThat(completed.receipt().orElseThrow().event()).isEqualTo(event); + assertThat(completed.receipt().orElseThrow().sourceState()).isEqualTo(advanced); + assertThat(completed.capture().sourceChange().canonicalBytes()) + .isEqualTo(change.canonicalBytes()); + assertThat(fences.readSourceChange(change).status()).isEqualTo("SOURCE_COMMITTED"); + return evidence.readCurrentIssuerAccountSources( + "firemud-account-service", account.getAccountUuid()); + } + + private List currentRoles() { + return in( + () -> { + operations.lockAccount(account.getId()); + var member = + members + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var provenance = + new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + return roles + .findForCanonicalUpdate( + account.getAccountUuid(), + tenantId, + provenance, + member.getId(), + member.getMembershipVersion()) + .orElseThrow() + .roles(); + }); + } + + private long membershipCount() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + account.getId(), + tenantId)) + .get(0, Long.class); + } + + private String stream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account.getAccountUuid() + + "/" + + tenantId; + } + + private void assertTransitionCount(long expected) { + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + stream())) + .isEqualTo(expected); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + tenantId)) + .isEqualTo(expected); + } + + private List state(String request) { + return List.of( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + request)) + .get(0, String.class), + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(json_agg(m)::text, '[]') FROM account_tenant_membership m WHERE account_id = ? AND tenant_uuid = ?", + account.getId(), + tenantId)) + .get(0, String.class), + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(json_agg(e ORDER BY outbox_sequence)::text, '[]') FROM account_authority_outbox_events e WHERE outbox_stream_key = ?", + stream())) + .get(0, String.class), + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(json_agg(to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text, '[]') FROM account_audit_outbox a WHERE tenant_uuid = ?", + tenantId)) + .get(0, String.class)); + } + + private T in(Supplier work) { + return transaction.execute(status -> work.get()); + } + } + + private static final class FixtureClock extends Clock { + private final Clock delegate; + private Duration offset = Duration.ZERO; + + private FixtureClock(Clock delegate) { + this.delegate = delegate; + } + + @Override + public java.time.ZoneId getZone() { + return java.time.ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return delegate.instant().plus(offset); + } + } + @Test void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); @@ -478,7 +2315,7 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test - void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumersHeld() + void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "auth-uuid-" + suffix; @@ -569,58 +2406,35 @@ void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumers assertThat(bootstrapClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); assertThat(bootstrapClaims.get("accountId", String.class)) .isEqualTo(persistedAccountUuid.toString()); + // Controlled complete empty source; caller identity and Redis session reads remain real. + var emptyTargets = org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + org.mockito.Mockito.when( + emptyTargets.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), "test"); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of())); + }); + var unusedEntitlements = org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); + canonicalFacade.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner( + new AccountPlayerBootstrapCallerVerifier( + jwtUtil, accountRepository, realAccountSessions), + emptyTargets, + unusedEntitlements, + Clock.systemUTC())); String passwordBootstrap = bootstrapData.path("bootstrapToken").asText(); - assertThat(bootstrapClaims.getAudience()).containsExactly("player-bootstrap"); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, passwordBootstrap)) - .isTrue(); - HttpResponse heldPasswordWorlds = bootstrapWorlds(passwordBootstrap); - assertThat(heldPasswordWorlds.statusCode()).isEqualTo(503); - assertThat(heldPasswordWorlds.body()).contains("AUTH_UNAVAILABLE"); - // This foundation has genuine Account identity/session issuance but no public selector or - // admission composition. The complete positive public journeys are retained in the successor. - for (Runnable held : - List.of( - () -> accountService.listBootstrapWorlds(passwordBootstrap), - () -> accountService.listBootstrapRealms(passwordBootstrap, "world"), - () -> - accountService.listBootstrapCharacters( - passwordBootstrap, "world", "production", "uncomposed-scope"), - () -> - accountService.joinPublicProduction( - passwordBootstrap, - new JoinPublicProductionRequest("uncomposed-scope", "foundation-join")), - () -> accountService.issueDirectTextConnectScope(null, null), - () -> - accountService.joinPublicProductionFromGameSession( - null, - new JoinPublicProductionRequest("uncomposed-scope", "foundation-direct-join")), - () -> - accountService.issueConnectToken( - passwordBootstrap, - new ConnectTokenRequest("uncomposed-scope", "foundation-connect")))) { - assertThatThrownBy(held::run) - .isInstanceOf(AuthenticationException.class) - .extracting(value -> ((AuthenticationException) value).getCode()) - .isEqualTo("AUTH_UNAVAILABLE"); - } - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", - numericAccountId)) - .isEqualTo(0L); - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_connect_scope_records WHERE account_id = ?", - numericAccountId)) - .isEqualTo(0L); - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_join_operations WHERE account_id = ?", - numericAccountId)) - .isEqualTo(0L); + assertThat(bootstrapWorlds(passwordBootstrap).statusCode()).isEqualTo(200); invalidateBootstrapSession(numericAccountId, passwordBootstrap); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, passwordBootstrap)) - .isFalse(); + HttpResponse expiredPassword = bootstrapWorlds(passwordBootstrap); + assertThat(expiredPassword.statusCode()).isEqualTo(401); + assertThat(expiredPassword.body()).contains("CONNECT_CONTEXT_INVALID"); accountService.requestEmailVerification(email); String verificationToken = @@ -678,14 +2492,9 @@ void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumers "Expected challenge-count record") .get(0, Long.class)) .isZero(); - assertThat(otpClaims.getAudience()).containsExactly("player-bootstrap"); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, otpBootstrap)).isTrue(); - HttpResponse heldOtpWorlds = bootstrapWorlds(otpBootstrap); - assertThat(heldOtpWorlds.statusCode()).isEqualTo(503); - assertThat(heldOtpWorlds.body()).contains("AUTH_UNAVAILABLE"); + assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(200); invalidateBootstrapSession(numericAccountId, otpBootstrap); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, otpBootstrap)) - .isFalse(); + assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(401); // Obtain a fresh real challenge: bootstrap issuance consumed the preceding one. accountService.requestEmailLoginOtp(email); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 1f5d79c7b6..a6bceb3f40 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -5,11 +5,13 @@ import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.Status; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.IOException; import java.net.URI; @@ -21,27 +23,79 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.cert.CertificateEncodingException; +import java.time.Clock; +import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.accountservice.client.GameSessionClient; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterPeerInterceptor; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadGrpcService; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadService; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.service.impl.CharacterServiceImpl; import net.firedevops.firemud.entitymanagement.service.impl.EntityManagementGrpcService; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; 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.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -62,11 +116,15 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.http.HttpHeaders; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -75,10 +133,12 @@ import tools.jackson.databind.json.JsonMapper; /** - * Composes real Account bootstrap HTTP with its mTLS Entity roster client and real Entity storage. - * Game Session target reads, test-owned membership rows, and test PKI are controlled fixtures; this - * proves neither World-owned active lifecycle nor public admission or first OPEN. Entity RPCs not - * used by ordinary roster reads remain mocked. + * Real Account HTTP registration/bootstrap/REALMS/CHARS, Redis credential lookup, canonical Account + * JOIN owners and Entity/Saga PostgreSQL assignment/discovery, with Account-to-Entity-to-GS mTLS. + * Account-side GS target/World observations and complete upstream publication/COMMITTED owner bytes + * are controlled fixtures. Assignment eligibility and local PKI are also controlled: this does not + * execute publication, GS/World owner stores, production custody, admission or first OPEN. The + * ordinary RPC is retained only for a separate numeric-selector refusal/retention proof. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -97,17 +157,9 @@ class BootstrapCharacterUuidEntityCompositionIntegrationTest { private static final String TEST_ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; private static final String TEST_ENTITY_PEER = "spiffe://firemud/ns/test/sa/entity-management-service"; - private static final long TARGET_TENANT_ID = 1L; - private static final long TARGET_GAME_INSTANCE_ID = 44L; - private static final String WORLD_SLUG = "uuid-bootstrap-proof"; - private static final String REALM_SLUG = "production"; - private static final UUID TARGET_REALM_ID = - UUID.fromString("d8f8de2e-89fd-4432-8cb4-93f241f56af6"); - private static final UUID TARGET_NAMESPACE_ID = - UUID.fromString("f711c0c9-c1fc-46fb-8ff2-1af7c4d96a67"); private static final long RETAINED_NUMERIC_ACCOUNT_ID = 98765L; - private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final AccountBootstrapRosterFixture.Fixture SOURCE = createSource(); private static final Path PKI_DIRECTORY = createTemporaryDirectory(); private static final LoopbackMtlsTestPki.Pki TEST_PKI = createTestPki(); private static final CommonGrpcClientProperties ACCOUNT_CLIENT_TLS = createAccountClientTls(); @@ -138,94 +190,382 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int accountHttpPort; @Autowired private DSLContext accountDsl; @Autowired private JwtUtil jwtUtil; - - @MockitoBean private GameSessionClient gameSessionClient; + @Autowired private AccountServiceImpl facade; + @Autowired private AccountRepository accounts; + @Autowired private AccountAuthorityGenerationRepository generations; + @Autowired private AccountAuthoritySourceEvidenceRepository accountSources; + @Autowired private FreshTenantIdentityAssociationRepository tenants; + @Autowired private AccountTenantMembershipRepository members; + @Autowired private AccountConnectScopeRepository scopes; + @Autowired private AccountTenantAuthorityEventRepository tenantEvents; + @Autowired private AccountDemoTenantEntitlementRepository demos; + @Autowired private AccountCanonicalFirstJoinTerminalCoordinator terminal; + @Autowired private AccountTokenProperties tokenProperties; + @Autowired private SessionService sessions; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private LoggingAdminClient loggingAdminClient; @MockitoBean private JavaMailSender mailSender; - private final JsonMapper jsonMapper = JsonMapper.builder().build(); @org.junit.jupiter.api.AfterAll - static void stopEntityRuntime() throws InterruptedException { + static void stopEntityRuntime() throws Exception { EntityRuntime runtime = entityRuntime; if (runtime != null) { runtime.server().shutdownNow(); assertThat(runtime.server().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + runtime.ownerClient().close(); + runtime.sourceServer().shutdownNow(); + assertThat(runtime.sourceServer().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); runtime.meters().close(); } - if (entityPostgres.isRunning()) { - entityPostgres.stop(); - } + if (entityPostgres.isRunning()) entityPostgres.stop(); } @org.junit.jupiter.api.Test - void bootstrapCharactersUsePersistedUuidAcrossHttpAndRealEntityOwnerReads() throws Exception { - stubControlledCurrentTarget(); - + void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtlsReads() + throws Exception { + var entity = requireEntityRuntime(); String suffix = UUID.randomUUID().toString().substring(0, 8); TestAccount ownerA = registerAccount("uuid-owner-a-" + suffix); TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix); assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid()); - seedAdmittingMembership(ownerA.storageId()); - seedAdmittingMembership(ownerB.storageId()); - seedActiveSubscription(ownerA.storageId()); - - EntityRuntime entity = requireEntityRuntime(); - String ownerACharacterName = "owned-by-a-" + suffix; - String ownerBCharacterName = "owned-by-b-" + suffix; - String wrongTenantCharacterName = "wrong-tenant-a-" + suffix; - var ownerACharacter = - saveOrdinaryCharacter( - entity, TARGET_TENANT_ID, ownerA.accountUuid(), ownerACharacterName, "shared-live"); - var ownerBCharacter = - saveOrdinaryCharacter( - entity, TARGET_TENANT_ID, ownerB.accountUuid(), ownerBCharacterName, "shared-live"); - var wrongTenantCharacter = - saveOrdinaryCharacter( - entity, - TARGET_TENANT_ID + 1, - ownerA.accountUuid(), - wrongTenantCharacterName, - "shared-live"); - - assertOrdinaryUuidRowIsQuarantined(entity, ownerACharacter.getId(), ownerA.accountUuid()); - assertOrdinaryUuidRowIsQuarantined(entity, ownerBCharacter.getId(), ownerB.accountUuid()); - assertOrdinaryUuidRowIsQuarantined(entity, wrongTenantCharacter.getId(), ownerA.accountUuid()); + configureCanonicalAccountOwners(); + initializeMemberAuthority(ownerA); + initializeMemberAuthority(ownerB); + String tokenA = issuePlayerBootstrap(ownerA); + String tokenB = issuePlayerBootstrap(ownerB); + String scopeA = discoverConnectScope(ownerA, tokenA); + String scopeB = discoverConnectScope(ownerB, tokenB); + // Existing canonical JOIN is invoked as an owner composition, not a newly exposed HTTP route. + var joinedA = + facade.joinPublicProduction( + tokenA, new JoinPublicProductionRequest(scopeA, UUID.randomUUID().toString())); + var joinedB = + facade.joinPublicProduction( + tokenB, new JoinPublicProductionRequest(scopeB, UUID.randomUUID().toString())); + assertThat(joinedA.success()).isTrue(); + assertThat(joinedB.success()).isTrue(); + assertThat(joinedA.tenantId()).isEqualTo(SOURCE.target().tenantUuid()); + assertThat(joinedA.membershipVersion()).isEqualTo(2L); + assertThat(joinedB.membershipVersion()).isEqualTo(2L); + assertThat( + accountDsl + .fetch( + "SELECT role_identifier FROM account_tenant_membership_role_snapshot_roles roles " + + "JOIN account_tenant_membership member ON member.id = roles.membership_id " + + "WHERE member.tenant_uuid = ? ORDER BY member.id", + SOURCE.target().tenantUuid()) + .getValues(0, String.class)) + .containsExactly("player", "player"); + try (var client = newRosterClient()) { + client.init(); + facade.setAccountBootstrapRosterReadClient(client); + var beforeEmpty = entityRows(entity); + assertThat(listBootstrapCharacters(tokenA, scopeA).isEmpty()).isTrue(); + assertThat(entityRows(entity)).isEqualTo(beforeEmpty); + } + UUID actorA = assign(entity, ownerA, SOURCE.target(), "owned-by-a-" + suffix); + UUID actorB = assign(entity, ownerB, SOURCE.target(), "owned-by-b-" + suffix); + entity.dsl().execute("UPDATE characters SET level = 12 WHERE character_uuid = ?", actorA); + assertThat( + entity + .dsl() + .fetchValue("SELECT level FROM characters WHERE character_uuid = ?", actorB)) + .isEqualTo(0); + var anotherNamespace = + CanonicalGameplayRosterTarget.fromWire( + SOURCE.target().toWire().toBuilder() + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString()) + .build()); + var anotherTenant = + CanonicalGameplayRosterTarget.fromWire( + SOURCE.target().toWire().toBuilder() + .setTenantUuid(UUID.randomUUID().toString()) + .build()); + assign(entity, ownerA, anotherNamespace, "wrong-namespace-" + suffix); + assign(entity, ownerA, anotherTenant, "wrong-tenant-" + suffix); + var quarantined = saveOrdinaryCharacter(entity, ownerA.accountUuid(), "quarantined-" + suffix); + assertOrdinaryUuidRowIsQuarantined(entity, quarantined.getId(), ownerA.accountUuid()); + var entityBefore = entityRows(entity); var retainedBefore = retainedNumericOwnerRow(entity); - assertThat(retainedBefore).hasSize(1); - - String ownerAToken = issuePlayerBootstrap(ownerA); - String ownerBToken = issuePlayerBootstrap(ownerB); - String ownerAScope = discoverConnectScope(ownerA, ownerAToken); - String ownerBScope = discoverConnectScope(ownerB, ownerBToken); + int ownerReadsBefore = entity.ownerReads().get(); - JsonNode ownerACharacters = listBootstrapCharacters(ownerAToken, ownerAScope); - JsonNode ownerBCharacters = listBootstrapCharacters(ownerBToken, ownerBScope); - - assertThat(characterNames(ownerACharacters)).containsExactly(ownerACharacterName); - assertThat(characterNames(ownerACharacters)) - .doesNotContain(ownerBCharacterName, wrongTenantCharacterName); - assertThat(characterNames(ownerBCharacters)).containsExactly(ownerBCharacterName); - assertThat(characterNames(ownerBCharacters)).doesNotContain(ownerACharacterName); + try (var client = newRosterClient()) { + client.init(); + facade.setAccountBootstrapRosterReadClient(client); + JsonNode actorsA = listBootstrapCharacters(tokenA, scopeA); + JsonNode actorsB = listBootstrapCharacters(tokenB, scopeB); + assertThat(characterNames(actorsA)).containsExactly("owned-by-a-" + suffix); + assertThat(characterNames(actorsB)).containsExactly("owned-by-b-" + suffix); + assertThat(actorsA.get(0).path("characterId").asText()).isEqualTo(actorA.toString()); + assertThat(actorsB.get(0).path("characterId").asText()).isEqualTo(actorB.toString()); + assertThat(actorsA.get(0).path("level").asInt()).isEqualTo(12); + assertThat(actorsB.get(0).path("level").asInt()).isZero(); + assertThat(actorsA.get(0).has("level")).isTrue(); + assertThat(actorsB.get(0).has("level")).isTrue(); + assertThat(actorsA.get(0).path("stateScope").asText()).isEqualTo("SHARED"); + assertThat(actorsA.get(0).path("characterCreationPolicy").asText()) + .isEqualTo("PRESEEDED_ONLY"); + var crossOwner = charactersResponse(tokenA, scopeB); + assertThat(crossOwner.statusCode()).isBetween(400, 499); + assertThat(jsonMapper.readTree(crossOwner.body()).path("error").path("code").asText()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + } + assertThat(entity.ownerReads().get() - ownerReadsBefore).isEqualTo(4); + assertThat(entityRows(entity)).isEqualTo(entityBefore); + assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); + assertThat( + accountDsl.fetchValue( + "SELECT COUNT(*) FROM account_tenant_membership WHERE tenant_uuid = ?", + SOURCE.target().tenantUuid())) + .isEqualTo(2L); + assertThat( + accountDsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + SOURCE.target().tenantUuid())) + .isEqualTo(2L); + assertThat( + accountDsl.fetchValue( + "SELECT COUNT(*) FROM account_join_operations WHERE account_uuid IN (?, ?) AND status = 'COMMITTED'", + ownerA.accountUuid(), + ownerB.accountUuid())) + .isEqualTo(2L); + } - var retainedAccountIdRequest = + @org.junit.jupiter.api.Test + void retainedNumericSelectorIsRefusedByOrdinaryRpcWithoutRewritingItsRow() throws Exception { + var entity = requireEntityRuntime(); + var retainedBefore = retainedNumericOwnerRow(entity); + assertThat(retainedBefore).hasSize(1); + var request = ListCharactersByAccountRequest.newBuilder() - .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setTenantId("1") .setAccountId(Long.toString(RETAINED_NUMERIC_ACCOUNT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setGameInstanceId("44") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build(); - var retainedOwnerResponse = listCharactersDirectlyAsAccount(retainedAccountIdRequest); - assertThat(retainedOwnerResponse.hasError()).isTrue(); - assertThat(retainedOwnerResponse.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(retainedOwnerResponse.getCharactersList()).isEmpty(); + var response = listCharactersDirectlyAsAccount(request); + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(response.getCharactersList()).isEmpty(); assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); } + private void configureCanonicalAccountOwners() { + var transaction = new TransactionTemplate(transactionManager); + var target = accountTarget(); + var creationRequest = UUID.randomUUID(); + var operation = UUID.randomUUID(); + String key = "b-" + operation.toString().replace("-", ""); + String digest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, creationRequest, key, "Bootstrap composition", null); + long rowId = 101L; + var source = + new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + creationRequest, + operation, + digest, + target.canonicalTenantId(), + rowId, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + creationRequest, + operation, + digest, + target.canonicalTenantId(), + rowId, + key, + "NEW_GAME_ROW")); + transaction.executeWithoutResult( + status -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(target.canonicalTenantId()); + accountSources.initializeIssuerIfAbsent("firemud-account-service"); + demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + target.canonicalTenantId(), + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(10L, 3L, 4096L)), + source); + }); + var targets = controlledAccountTargets(target); + var hosting = Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class); + var observer = Mockito.mock(StripeHostingSubscriptionObserver.class); + var clock = Clock.systemUTC(); + var entitlement = + new AccountPublicBootstrapEntitlementOwner( + tenantEvents, + new AccountHostingSubscriptionLifecycleService(hosting, observer, transactionManager), + demos, + transactionManager, + clock); + facade.setCanonicalPublicRealmScopeOwner( + new AccountCanonicalPublicRealmScopeOwner( + new AccountPlayerBootstrapCallerVerifier(jwtUtil, accounts, sessions), + targets, + entitlement, + accounts, + members, + tenants, + tenantEvents, + scopes, + jwtUtil, + tokenProperties, + clock, + transactionManager, + TEST_NAMESPACE)); + facade.setCanonicalScopeConsumers( + new AccountCanonicalConnectScopeReader(jwtUtil, scopes, transactionManager, clock), + targets, + tenantEvents, + demos, + hosting, + observer, + terminal, + TEST_NAMESPACE, + clock); + } + + private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Target target) { + var client = Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + Mockito.when(client.listVisiblePublicProductionAdmissionTargets(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), TEST_NAMESPACE); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target))); + }); + Mockito.when(client.resolvePublishedRealmAdmissionTarget(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + request, target)); + }); + Mockito.when(client.readPublishedRealmAdmissionOwner(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument(0, CanonicalGameplayRosterOwnerReadEvidence.Request.class); + var published = + Mockito.mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + Mockito.when(published.selector()).thenReturn(request); + Mockito.when(published.currentTarget()).thenReturn(target); + Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request)); + var world = Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); + Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); + Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); + Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); + return client; + } + + private void initializeMemberAuthority(TestAccount account) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.accountUuid(), SOURCE.target().tenantUuid()))); + } + + private static Target accountTarget() { + var target = SOURCE.target(); + var proof = SOURCE.evidence().gameSessionOwnerProof(); + var hold = proof.holdIdentity(); + var request = hold.request(); + return new Target( + TEST_NAMESPACE, + "bootstrap-tenant", + target.tenantUuid(), + target.worldSlug(), + "Earth", + target.realmUuid(), + target.realmSlug(), + "Main", + 1L, + 44L, + target.playableStateNamespaceId(), + "SHARED", + target.gameInstanceUuid(), + target.canonicalVersionUuid(), + 1L, + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, + false, + proof.terminalAt(), + "PRESEEDED_ONLY"); + } + + private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + var base = SOURCE.evidence().request(); + var expected = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + base.targetNamespace(), + base.canonicalTenantUuid(), + base.worldSlug(), + base.realmUuid(), + base.realmSlug(), + base.playableStateNamespaceUuid(), + base.playableStateScope(), + base.canonicalGameInstanceUuid(), + base.canonicalVersionUuid(), + base.expectedCatalogRevision(), + base.expectedPointerVersion(), + base.expectedActiveWorldEpoch()); + if (!request.equals(expected)) + throw new IllegalArgumentException("Controlled owner target mismatch"); + return new CanonicalGameplayRosterOwnerReadEvidence( + request, + SOURCE.target().admissionPointerSnapshotDigest(), + SOURCE.evidence().gameSessionOwnerProof(), + SOURCE.evidence().publishedPolicySetEvidence()); + } + private TestAccount registerAccount(String username) throws Exception { String email = username + "@example.com"; - HttpRequest request = + var request = HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/accounts")) .header(HttpHeaders.CONTENT_TYPE, "application/json") .POST( @@ -233,59 +573,18 @@ private TestAccount registerAccount(String username) throws Exception { jsonMapper.writeValueAsString( Map.of("username", username, "email", email, "password", "password123")))) .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + var response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - - String responseUuid = jsonMapper.readTree(response.body()).path("data").path("id").asText(); - UUID accountUuid = UUID.fromString(responseUuid); - Number accountId = - accountDsl - .resultQuery("SELECT id FROM accounts WHERE email = ?", email) - .fetchOne(0, Number.class); - assertThat(accountId).isNotNull(); - long storageId = accountId.longValue(); - assertThat( - accountDsl - .resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", storageId) - .fetchOne(0, UUID.class)) - .isEqualTo(accountUuid); - assertThat( - accountDsl - .resultQuery( - "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", storageId) - .fetchOne(0, Long.class)) - .isEqualTo(storageId); - assertThat( - accountDsl - .resultQuery("SELECT account_uuid_provenance FROM accounts WHERE id = ?", storageId) - .fetchOne(0, String.class)) - .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); - return new TestAccount(username, email, storageId, accountUuid); - } - - private void seedAdmittingMembership(long accountId) { - // This is test-owned Account state for the existing roster guard, not canonical membership - // proof. - accountDsl.execute( - "INSERT INTO account_tenant_membership " - + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " - + "membership_version, membership_authority_generation, authority_provenance) " - + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'SEEDED_DEMO')", - accountId, - TARGET_TENANT_ID); - } - - private void seedActiveSubscription(long accountId) { - accountDsl.execute( - "INSERT INTO subscription " - + "(account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'uuid-bootstrap-composition', 'active', ?, 1)", - accountId, - TARGET_TENANT_ID); + UUID id = + UUID.fromString(jsonMapper.readTree(response.body()).path("data").path("id").asText()); + var row = accounts.findByAccountUuid(id).orElseThrow(); + assertThat(row.getAccountUuidSourceNumericId()).isEqualTo(row.getId()); + assertThat(row.getAccountUuidProvenance().name()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + return new TestAccount(username, email, row.getId(), id); } private String issuePlayerBootstrap(TestAccount account) throws Exception { - HttpRequest request = + var request = HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/auth/player-bootstrap")) .header(HttpHeaders.CONTENT_TYPE, "application/json") .POST( @@ -293,142 +592,192 @@ private String issuePlayerBootstrap(TestAccount account) throws Exception { jsonMapper.writeValueAsString( Map.of("accountIdentifier", account.username(), "secret", "password123")))) .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + var response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - JsonNode data = jsonMapper.readTree(response.body()).path("data"); + var data = jsonMapper.readTree(response.body()).path("data"); assertThat(data.path("accountId").asText()).isEqualTo(account.accountUuid().toString()); - String bootstrapToken = data.path("bootstrapToken").asText(); - var claims = jwtUtil.parseToken(bootstrapToken).getPayload(); - assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); - return bootstrapToken; + String token = data.path("bootstrapToken").asText(); + assertThat(jwtUtil.parseToken(token).getPayload().getSubject()) + .isEqualTo(account.accountUuid().toString()); + return token; } - private String discoverConnectScope(TestAccount account, String bootstrapToken) throws Exception { - HttpRequest request = + private String discoverConnectScope(TestAccount account, String token) throws Exception { + var request = HttpRequest.newBuilder( - URI.create(accountBaseUrl() + "/auth/bootstrap/worlds/" + WORLD_SLUG + "/realms")) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + URI.create( + accountBaseUrl() + + "/auth/bootstrap/worlds/" + + SOURCE.target().worldSlug() + + "/realms")) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + var response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + // Preserve the HTTP assertion while exposing an owner/proxy exception otherwise hidden by + // the public INTERNAL_ERROR projection. This uses the same actual caller and owner setup. + org.assertj.core.api.Assertions.assertThatCode( + () -> facade.listBootstrapRealms(token, SOURCE.target().worldSlug())) + .as("REALMS owner composition after HTTP response: %s", response.body()) + .doesNotThrowAnyException(); + } assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - JsonNode realms = jsonMapper.readTree(response.body()).path("data"); - assertThat(realms.isArray()).isTrue(); + var realms = jsonMapper.readTree(response.body()).path("data"); assertThat(realms.size()).isEqualTo(1); - JsonNode realm = realms.get(0); - assertThat(realm.path("tenantId").asLong()).isEqualTo(TARGET_TENANT_ID); - String scope = realm.path("connectScopeId").asText(); + assertThat(realms.get(0).path("tenantId").asText()) + .isEqualTo(SOURCE.target().tenantUuid().toString()); + String scope = realms.get(0).path("connectScopeId").asText(); var claims = jwtUtil.parseToken(scope).getPayload(); assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); + assertThat(claims.get("scopeDigestVersion", Number.class).longValue()).isEqualTo(2L); + assertThat(claims.get("tenantId", String.class)) + .isEqualTo(SOURCE.target().tenantUuid().toString()); return scope; } - private JsonNode listBootstrapCharacters(String bootstrapToken, String connectScopeId) - throws Exception { - String encodedScope = URLEncoder.encode(connectScopeId, StandardCharsets.UTF_8); - HttpRequest request = + private HttpResponse charactersResponse(String token, String scope) throws Exception { + String encoded = URLEncoder.encode(scope, StandardCharsets.UTF_8); + var request = HttpRequest.newBuilder( URI.create( accountBaseUrl() + "/auth/bootstrap/worlds/" - + WORLD_SLUG + + SOURCE.target().worldSlug() + "/realms/" - + REALM_SLUG + + SOURCE.target().realmSlug() + "/characters?connectScopeId=" - + encodedScope)) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + + encoded)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - return jsonMapper.readTree(response.body()).path("data"); + return HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); } - private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( - ListCharactersByAccountRequest request) throws Exception { - EntityRuntime runtime = requireEntityRuntime(); - var identity = TEST_PKI.identity("account"); - ManagedChannel channel = - NettyChannelBuilder.forAddress("localhost", runtime.server().getPort()) - .sslContext( - GrpcSslContexts.forClient() - .trustManager(TEST_PKI.caCertificate()) - .keyManager( - identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) - .build()) - .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) - .build(); - try { - return EntityManagementServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .listCharactersByAccount(request); - } finally { - channel.shutdownNow(); - assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } + private JsonNode listBootstrapCharacters(String token, String scope) throws Exception { + var response = charactersResponse(token, scope); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + return jsonMapper.readTree(response.body()).path("data"); } - private void stubControlledCurrentTarget() { - var realm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug(WORLD_SLUG) - .setRealmSlug(REALM_SLUG) - .setDisplayName("Controlled UUID composition target") - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setRealmId(TARGET_REALM_ID.toString()) - .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var pointer = - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug(WORLD_SLUG) - .setRealmSlug(REALM_SLUG) - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setRealmId(TARGET_REALM_ID.toString()) - .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - Mockito.when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); - Mockito.when(gameSessionClient.getAdmissionPointer(TARGET_TENANT_ID, WORLD_SLUG, REALM_SLUG)) - .thenReturn(pointer); + private static UUID assign( + EntityRuntime runtime, + TestAccount account, + CanonicalGameplayRosterTarget target, + String name) { + UUID operation = UUID.randomUUID(); + var evidence = + new PreseededActorAssignmentOwnerEvidence( + operation, + account.accountUuid(), + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 4L, + "1".repeat(64), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef()); + var request = + new PreseededActorAssignmentRequest( + operation, + account.accountUuid(), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, name), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + var result = + new TransactionTemplate(runtime.transactionManager()) + .execute( + status -> + runtime + .characterRepository() + .assignPreseededActor( + request, + evidence, + new RuntimeAccountIdentityEvidence( + 1, + TEST_NAMESPACE, + operation, + account.accountUuid(), + account.storageId(), + "ACCOUNT_REPOSITORY_INSERT"), + request.mutationIntentDigest())); + assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat( + runtime + .dsl() + .fetchValue( + "SELECT actor_identity_status FROM characters WHERE character_uuid = ?", + result.characterUuid())) + .isEqualTo("OWNER_RESOLVED"); + return result.characterUuid(); } private static net.firedevops.firemud.entitymanagement.entity.Character saveOrdinaryCharacter( - EntityRuntime runtime, - long tenantId, - UUID accountUuid, - String name, - String playableStateKey) { + EntityRuntime runtime, UUID account, String name) { var character = new net.firedevops.firemud.entitymanagement.entity.Character(); - character.setTenantId(tenantId); - character.setAccountUuid(accountUuid); - character.setPlayableStateKey(playableStateKey); + character.setTenantId(1L); + character.setAccountUuid(account); + character.setPlayableStateKey("shared-live"); character.setName(name); return runtime.characterRepository().save(character); } private static void assertOrdinaryUuidRowIsQuarantined( - EntityRuntime runtime, long characterId, UUID accountUuid) { - var persisted = runtime.characterRepository().findById(characterId).orElseThrow(); - assertThat(persisted.getAccountUuid()).isEqualTo(accountUuid); - assertThat(persisted.getAccountId()).isNull(); - assertThat(persisted.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); - assertThat(persisted.getActorIdentity().tenantUuid()).isNull(); - assertThat(persisted.getActorIdentity().playableStateNamespaceId()).isNull(); + EntityRuntime runtime, long id, UUID account) { + var character = runtime.characterRepository().findById(id).orElseThrow(); + assertThat(character.getAccountUuid()).isEqualTo(account); + assertThat(character.getAccountId()).isNull(); + assertThat(character.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); + assertThat(character.getActorIdentity().tenantUuid()).isNull(); + assertThat(character.getActorIdentity().playableStateNamespaceId()).isNull(); + } + + private static Map> entityRows(EntityRuntime runtime) { + var rows = new LinkedHashMap>(); + for (String table : + List.of( + "characters", + "entity_playable_state_namespace_scopes", + "entity_preseeded_actor_assignment_operations", + "entity_canonical_gameplay_roster_snapshots", + "entity_canonical_gameplay_roster_snapshot_actors", + "entity_canonical_roster_original_selections", + "entity_canonical_roster_admissions", + "entity_canonical_roster_retention_references")) { + rows.put( + table, + runtime + .dsl() + .fetch( + "SELECT to_jsonb(t)::text || ':' || xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class)); + } + return rows; } private static List> retainedNumericOwnerRow(EntityRuntime runtime) { @@ -453,133 +802,214 @@ private static String entityServiceTarget() { return "localhost:" + requireEntityRuntime().server().getPort(); } + private static AccountBootstrapRosterReadClient newRosterClient() { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService(entityServiceTarget()); + return new AccountBootstrapRosterReadClient( + endpoints, ACCOUNT_CLIENT_TLS, new GrpcChannelFactory(), TEST_NAMESPACE); + } + private static synchronized EntityRuntime requireEntityRuntime() { - if (entityRuntime != null) { - return entityRuntime; - } + if (entityRuntime != null) return entityRuntime; try { - if (!entityPostgres.isRunning()) { - entityPostgres.start(); - } - var dataSource = + if (!entityPostgres.isRunning()) entityPostgres.start(); + var ds = new DriverManagerDataSource( entityPostgres.getJdbcUrl(), entityPostgres.getUsername(), entityPostgres.getPassword()); - String migrationProperty = - System.getProperty("firemud.entity-management.migration-directory"); - if (migrationProperty == null || migrationProperty.isBlank()) { - throw new IllegalStateException("Entity migration directory property is missing or blank"); - } - Path migrationDirectory = Path.of(migrationProperty); - if (!Files.isDirectory(migrationDirectory)) { - throw new IllegalStateException( - "Entity migration directory is unavailable: " + migrationDirectory); - } - entityMigrationConfiguration(dataSource, migrationDirectory) + String configured = System.getProperty("firemud.entity-management.migration-directory"); + if (configured == null || !Files.isDirectory(Path.of(configured))) + throw new IllegalStateException("Entity migration directory is unavailable"); + var migrations = Path.of(configured); + entityMigrationConfiguration(ds, migrations) .target(MigrationVersion.fromVersion("1023")) .load() .migrate(); - var jdbc = new JdbcTemplate(dataSource); + var jdbc = new JdbcTemplate(ds); jdbc.update( - "INSERT INTO characters (tenant_id, account_id, name) VALUES (?, ?, ?)", - TARGET_TENANT_ID, - RETAINED_NUMERIC_ACCOUNT_ID, - "retained-numeric-owner"); - entityMigrationConfiguration(dataSource, migrationDirectory).load().migrate(); - - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + "INSERT INTO characters (tenant_id, account_id, name) VALUES (1, ?, 'retained-numeric-owner')", + RETAINED_NUMERIC_ACCOUNT_ID); + entityMigrationConfiguration(ds, migrations).load().migrate(); + var manager = new DataSourceTransactionManager(ds); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(ds), SQLDialect.POSTGRES); var repository = new CharacterRepository(dsl); - var stateKeys = new PlayableStateKeyResolver(); - var meters = new SimpleMeterRegistry(); - var characterService = - new CharacterServiceImpl( - repository, - Mappers.getMapper(CharacterMapper.class), - new ConcurrentMapCacheManager("characterGraph"), - meters, - stateKeys, - new ScopedCharacterResolver(repository, stateKeys)); - var receiver = - new EntityManagementGrpcService( - Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), - characterService, - Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService - .class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.impl - .EntityMutationEffectReplayService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService - .class), - Mockito.mock( - net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), - meters, - Mockito.mock( - net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + var reads = new AtomicInteger(); + Server sourceServer = startSourceServer(reads); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + sourceServer.getPort()); + var client = + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("entity-client")), + new GrpcChannelFactory(), TEST_NAMESPACE); - var entityIdentity = TEST_PKI.identity("entity"); + client.init(); + var service = + new AccountBootstrapRosterReadService( + new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, TEST_NAMESPACE), + repository, + manager); + var meters = new SimpleMeterRegistry(); + var identity = TEST_PKI.identity("entity"); Server server = NettyServerBuilder.forPort(0) .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer( - entityIdentity.privateKey(), entityIdentity.certificate())) + identity.privateKey(), identity.certificate())) .trustManager(TEST_PKI.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) + .addService( + ServerInterceptors.intercept( + new AccountBootstrapRosterReadGrpcService(service, TEST_NAMESPACE), + new AccountBootstrapRosterPeerInterceptor(TEST_NAMESPACE))) + .addService( + ServerInterceptors.intercept( + ordinaryReceiver(repository, meters), new GrpcPeerIdentityInterceptor())) .build() .start(); - entityRuntime = new EntityRuntime(repository, jdbc, server, meters); + entityRuntime = + new EntityRuntime( + repository, jdbc, dsl, manager, server, sourceServer, client, reads, meters); return entityRuntime; - } catch (IOException | RuntimeException failure) { - if (entityPostgres.isRunning()) { - entityPostgres.stop(); - } + } catch (IOException | CertificateEncodingException | RuntimeException failure) { + if (entityPostgres.isRunning()) entityPostgres.stop(); throw new IllegalStateException( "Could not start the real Entity mTLS owner fixture", failure); } } + private static Server startSourceServer(AtomicInteger reads) throws IOException { + var identity = TEST_PKI.identity("gs"); + return NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(TEST_PKI.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase() { + @Override + public void getCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace(TEST_NAMESPACE)) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + try { + var request = CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(wire); + var evidence = ownerEvidence(request); + reads.incrementAndGet(); + observer.onNext( + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request, evidence)); + observer.onCompleted(); + } catch (IllegalArgumentException invalid) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } + } + }, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static EntityManagementGrpcService ordinaryReceiver( + CharacterRepository repository, SimpleMeterRegistry meters) { + var stateKeys = new PlayableStateKeyResolver(); + var characters = + new CharacterServiceImpl( + repository, + Mappers.getMapper(CharacterMapper.class), + new ConcurrentMapCacheManager("characterGraph"), + meters, + stateKeys, + new ScopedCharacterResolver(repository, stateKeys)); + return new EntityManagementGrpcService( + Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), + characters, + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.impl.EntityMutationEffectReplayService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService.class), + Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + meters, + Mockito.mock(net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + TEST_NAMESPACE); + } + + private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( + ListCharactersByAccountRequest request) throws Exception { + var identity = TEST_PKI.identity("account"); + ManagedChannel channel = + NettyChannelBuilder.forAddress("localhost", requireEntityRuntime().server().getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(TEST_PKI.caCertificate()) + .keyManager( + identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) + .build()) + .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) + .build(); + try { + return EntityManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .listCharactersByAccount(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + private static FluentConfiguration entityMigrationConfiguration( - DriverManagerDataSource dataSource, Path migrationDirectory) { - FluentConfiguration configuration = + DriverManagerDataSource ds, Path directory) { + var config = Flyway.configure() - .dataSource(dataSource) - .locations( - "filesystem:" + migrationDirectory, - "filesystem:" - + migrationDirectory - .resolve( - "../../../../../../common-saga/src/main/resources/db/migration/saga") - .normalize()) + .dataSource(ds) + .table("flyway_schema_history_entity_management_service") + .locations("filesystem:" + directory, "classpath:db/migration/saga") .placeholders(Map.of("serviceSchema", "public")); - configuration + config .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); - return configuration; + return config; + } + + private static AccountBootstrapRosterFixture.Fixture createSource() { + try { + return AccountBootstrapRosterFixture.create(); + } catch (Exception failure) { + throw new ExceptionInInitializerError(failure); + } } private static Path createTemporaryDirectory() { try { return Files.createTempDirectory("firemud-account-entity-composition-"); - } catch (Exception failure) { + } catch (IOException failure) { throw new ExceptionInInitializerError(failure); } } @@ -590,7 +1020,10 @@ private static LoopbackMtlsTestPki.Pki createTestPki() { PKI_DIRECTORY, "Account-to-Entity composition proof CA", new LoopbackMtlsTestPki.IdentitySpec("entity", TEST_ENTITY_PEER, true), - new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false)); + new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec("entity-client", TEST_ENTITY_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "gs", "spiffe://firemud/ns/test/sa/game-session-service", true)); } catch (Exception failure) { throw new ExceptionInInitializerError(failure); } @@ -599,7 +1032,7 @@ private static LoopbackMtlsTestPki.Pki createTestPki() { private static CommonGrpcClientProperties createAccountClientTls() { try { return TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("account")); - } catch (CertificateEncodingException | java.io.IOException failure) { + } catch (CertificateEncodingException | IOException failure) { throw new ExceptionInInitializerError(failure); } } @@ -609,6 +1042,11 @@ private record TestAccount(String username, String email, long storageId, UUID a private record EntityRuntime( CharacterRepository characterRepository, JdbcTemplate jdbc, + DSLContext dsl, + DataSourceTransactionManager transactionManager, Server server, + Server sourceServer, + GameSessionCanonicalGameplayRosterOwnerReadClient ownerClient, + AtomicInteger ownerReads, SimpleMeterRegistry meters) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index e40b79cd69..a34cacc9ab 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -363,6 +363,444 @@ void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { assertThat(scopeRowCount(setupDsl, v2Scope.connectScopeId())).isEqualTo(1); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite( + boolean bound) { + JournalFixture f = journalFixture(); + if (bound) + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + else + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); + var original = f.read(); + String outcome = bound ? "IDEMPOTENCY_CONFLICT" : "CONNECT_SCOPE_INVALID"; + var failed = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); + assertThat(failed.status()).isEqualTo("FAILED"); + assertThat(failed.outcome()).isEqualTo(outcome); + assertThat(failed.intentDigest()).isEqualTo(original.intentDigest()); + assertThat(failed.scopeEvidence()).isEqualTo(original.scopeEvidence()); + assertThat(failed.requestDigest()).isEqualTo(original.requestDigest()); + assertThat(failed.requestDigestVersion()).isEqualTo(original.requestDigestVersion()); + assertThat(failed.allowPublicJoin()).isEqualTo(original.allowPublicJoin()); + assertThat(failed.entitlementVersion()).isEqualTo(original.entitlementVersion()); + assertThat(failed.entitlementAuthorityAvailability()) + .isEqualTo(bound ? "AVAILABLE" : "NOT_EVALUATED"); + assertThat(failed.lastAttemptFailureCode()).isNull(); + assertThat(failed.membershipId()).isNull(); + assertThat(failed.terminalProof()).isNull(); + String retained = f.bytes(); + var replay = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); + assertThat(replay).isEqualTo(failed); + assertThat(f.bytes()).isEqualTo(retained); + f.transaction() + .executeWithoutResult( + status -> + assertThat( + f.operations().insertCanonicalIntent(f.requestId(), f.scope(), f.caller())) + .isFalse()); + if (bound) { + var policyReplay = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23)); + assertThat(policyReplay).isEqualTo(failed); + } else { + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23))) + .isInstanceOf( + AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + } + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + f.caller(), + "TENANT_BILLING_BLOCKED"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), + f.scope(), + f.caller(), + "ENTITLEMENT_UNAVAILABLE"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.dsl() + .execute( + "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE request_id = ?", + f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(retained); + f.assertNoSuccessEffects(); + } + + @Test + void + boundPendingUnavailableDiagnosticsNeverDowngradePolicyAndExactRecoveryOnlyClearsDiagnostics() { + JournalFixture f = journalFixture(); + var bound = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23)); + var unavailable = + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); + assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(unavailable.requestDigest()).isEqualTo(bound.requestDigest()); + assertThat(unavailable.entitlementVersion()).isEqualTo(23); + assertThat(unavailable.allowPublicJoin()).isTrue(); + assertThat(unavailable.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + var targetUnavailable = + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalAttemptFailure( + f.requestId(), + f.scope(), + f.caller(), + "NOT_EVALUATED", + "AUTH_UNAVAILABLE")); + assertThat(targetUnavailable.requestDigest()).isEqualTo(bound.requestDigest()); + assertThat(targetUnavailable.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); + String beforeConflict = f.bytes(); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 24))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThat(f.bytes()).isEqualTo(beforeConflict); + var recovered = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23)); + assertThat(recovered.requestDigest()).isEqualTo(bound.requestDigest()); + assertThat(recovered.entitlementVersion()).isEqualTo(bound.entitlementVersion()); + assertThat(recovered.allowPublicJoin()).isEqualTo(bound.allowPublicJoin()); + assertThat(recovered.lastAttemptAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(recovered.lastAttemptFailureCode()).isNull(); + String recoveredBytes = f.bytes(); + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + assertThat(f.bytes()).isEqualTo(recoveredBytes); + f.assertNoSuccessEffects(); + } + + @Test + void definitivePublicJoinDenialRetainsItsAlreadyBoundNegativePolicy() { + JournalFixture f = journalFixture(); + var deniedPolicy = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), false, 23)); + var failed = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + f.caller(), + "PUBLIC_PRODUCTION_ADMISSION_DENIED")); + assertThat(failed.status()).isEqualTo("FAILED"); + assertThat(failed.allowPublicJoin()).isFalse(); + assertThat(failed.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(failed.requestDigest()).isEqualTo(deniedPolicy.requestDigest()); + assertThat(failed.entitlementVersion()).isEqualTo(deniedPolicy.entitlementVersion()); + f.assertNoSuccessEffects(); + } + + @Test + void failedJournalRejectsConflictingCallerRequestAndRetainedScopeWithoutRewritingReceipt() { + JournalFixture f = journalFixture(); + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + String retained = f.bytes(); + var alternate = + canonicalScope("different-canonical-bearer", f.scope().accountId(), f.scope().tenantId()); + f.transaction() + .executeWithoutResult( + status -> + f.scopes() + .insertCanonical( + f.accountId(), alternate, f.read().scopeEvidence().tenantProvenance())); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + "different-caller", + "CONNECT_SCOPE_INVALID"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + "different-global-request", + f.scope(), + f.caller(), + "CONNECT_SCOPE_INVALID"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), alternate, f.caller(), "CONNECT_SCOPE_INVALID"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThat(f.bytes()).isEqualTo(retained); + } + + @Test + void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerminalMutation() { + JournalFixture f = journalFixture(); + String original = f.bytes(); + for (String change : + java.util.List.of( + "status = 'FAILED', outcome = 'ENTITLEMENT_UNAVAILABLE'", + "status = 'FAILED', outcome = 'CONNECT_SCOPE_INVALID', membership_id = 1", + "status = 'COMMITTED', outcome = 'JOINED'", + "intent_digest = 'sha256:" + "b".repeat(64) + "'")) { + assertThatThrownBy( + () -> + f.dsl() + .execute( + "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", + f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(original); + } + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + String bound = f.bytes(); + for (String change : + java.util.List.of( + "entitlement_authority_availability = 'UNAVAILABLE'", + "entitlement_version = 24", + "request_digest = NULL", + "last_attempt_authority_availability = 'UNAVAILABLE', last_attempt_failure_code = NULL")) { + assertThatThrownBy( + () -> + f.dsl() + .execute( + "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", + f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(bound); + } + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + String terminal = f.bytes(); + assertThatThrownBy( + () -> + f.dsl() + .execute( + "DELETE FROM account_join_operations WHERE request_id = ?", f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl().execute("TRUNCATE account_join_operations")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(terminal); + f.assertNoSuccessEffects(); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction(boolean bound) { + JournalFixture f = journalFixture(); + if (bound) + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + String original = f.bytes(); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> { + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE"); + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID"); + throw new IllegalStateException("controlled canonical journal rollback"); + })) + .hasMessageContaining("controlled canonical journal rollback"); + assertThat(f.bytes()).isEqualTo(original); + var failed = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + assertThat(failed.status()).isEqualTo("FAILED"); + f.assertNoSuccessEffects(); + } + + private JournalFixture journalFixture() { + String schema = createSchema("canonical_join_scope_"); + var source = postgres.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext setup = DSL.using(source, SQLDialect.POSTGRES); + DSLContext owner = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + var account = + Objects.requireNonNull( + setup.fetchOne( + "INSERT INTO accounts (username, email, password_hash) VALUES ('journal-player', 'journal@example.test', 'controlled-hash') RETURNING id, account_uuid")); + long privateAccountId = account.get("id", Long.class); + UUID accountId = account.get("account_uuid", UUID.class); + var fresh = new FreshTenantIdentityAssociationRepository(owner, "prod"); + var tenant = freshTenantEvidence(); + transaction.executeWithoutResult(status -> fresh.importVerified(tenant)); + var scopes = + new AccountConnectScopeRepository(owner, mock(AccountTenantIdentityResolver.class), fresh); + var operations = new AccountJoinOperationRepository(owner, scopes); + var scope = canonicalScope(accountId, tenant.canonicalTenantId()); + String requestId = "journal-" + UUID.randomUUID(); + String caller = "controlled-journal-caller"; + transaction.executeWithoutResult( + status -> { + scopes.insertCanonical( + privateAccountId, + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.operationId(), + tenant.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, caller); + }); + return new JournalFixture( + setup, transaction, operations, scopes, scope, privateAccountId, requestId, caller); + } + + /** Physical journal storage proof only; supplied caller/scope selectors do not authenticate. */ + private record JournalFixture( + DSLContext dsl, + TransactionTemplate transaction, + AccountJoinOperationRepository operations, + AccountConnectScopeRepository scopes, + CanonicalJoinScopeV2 scope, + long accountId, + String requestId, + String caller) { + private CanonicalJoinOperationEvidence read() { + return Objects.requireNonNull( + transaction.execute( + status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow())); + } + + private String bytes() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + requestId)) + .get(0, String.class); + } + + private void assertNoSuccessEffects() { + for (String table : + java.util.List.of( + "account_tenant_membership", + "account_authority_outbox_events", + "account_audit_outbox")) assertThat(dsl.fetchCount(DSL.table(table))).isZero(); + assertThat(read().membershipId()).isNull(); + assertThat(read().terminalProof()).isNull(); + } + } + private static long scopeRowCount(DSLContext dsl, String connectScopeId) { return Objects.requireNonNull( dsl.fetchOne( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index d72151f370..d9a2cda093 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -10,10 +10,14 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -27,6 +31,8 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; @@ -36,7 +42,11 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; @@ -300,6 +310,342 @@ void terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether() { assertThat(operation.terminalProof()).isNull(); } + @Test + void activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays() { + Fixture fixture = newFixture(); + var original = fixture.commitFirstJoin(); + String nextRequest = fixture.prepareAnotherJoin(); + var result = fixture.commitExistingJoin(nextRequest); + var replay = fixture.commitExistingJoin(nextRequest); + + assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.membershipId()).isEqualTo(original.membershipId()); + assertThat(result.membershipVersion()).isEqualTo(2L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(result.terminalProof().eventSequence()).isEqualTo(1L); + assertThat(result.terminalProof().auditEventId()).isNull(); + assertThat(replay).isEqualTo(result); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.dsl.execute( + "UPDATE account_join_operations SET outcome_membership_version = 3 WHERE request_id = ?", + nextRequest))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void closingEnrollmentPreservesAnActiveMembersEventFreeJoinSnapshot() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + fixture.inTransaction( + () -> { + var current = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); + fixture.demoEntitlements.provision( + fixture.entitlementRequest(UUID.randomUUID(), current, false), + fixture.tenantEvidence); + return null; + }); + String requestId = fixture.prepareAnotherJoin(); + var result = fixture.commitExistingJoin(requestId); + assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.allowPublicJoin()).isFalse(); + assertThat(result.membershipVersion()).isEqualTo(2L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + + @Test + void activeNonAdmittingSnapshotWithoutPlayerRoleRemainsSuccessfulAndUnchanged() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + fixture.seedControlledMembershipSnapshot("ACTIVE", java.util.List.of()); + BrowserFacade browser = fixture.browserFacade(); + var selected = + browser.service().listBootstrapRealms(browser.bootstrapToken(), "world").getFirst(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), UUID.randomUUID().toString()); + var result = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.gameplayAdmissionAllowed()).isFalse(); + assertThat(result.membershipVersion()).isEqualTo(3L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(replay.gameplayAdmissionAllowed()).isFalse(); + assertThat(replay.replayed()).isTrue(); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + var roles = + fixture.inTransaction( + () -> + fixture + .roles + .findForCanonicalUpdate( + fixture.account.getAccountUuid(), + fixture.tenantUuid, + fixture.provenance, + member.getId(), + 3L) + .orElseThrow()); + assertThat(roles.roles()).isEmpty(); + assertThat(member.isGameplayAdmissionAllowed()).isFalse(); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(2L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + + @Test + void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { + Fixture fixture = newFixture(); + var checkpoint = fixture.writeAndPublish(); + assertThatThrownBy(() -> fixture.commitExistingJoin(fixture.requestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("precommitted transition"); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + var proof = + new AccountJoinOperationRepository.CanonicalJoinTerminalProof( + checkpoint.outboxStreamKey(), + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + null, + null, + null, + 1L, + member.getId(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration()); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.operations.commitCanonicalJoin( + fixture.requestId, + fixture.scope, + fixture.callerBinding, + "ALREADY_ACTIVE", + proof))) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.countAll("account_audit_outbox")).isZero(); + assertThat( + fixture + .inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()) + .status()) + .isEqualTo("PENDING"); + } + + @Test + void inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration() { + Fixture fixture = newFixture(); + var first = fixture.commitFirstJoin(); + fixture.seedControlledInactiveOwnerSnapshot(); + String restoreRequest = fixture.prepareAnotherJoin(); + var result = fixture.commitExistingJoin(restoreRequest); + var replay = fixture.commitExistingJoin(restoreRequest); + + assertThat(result.outcome()).isEqualTo("JOINED"); + assertThat(result.membershipId()).isEqualTo(first.membershipId()); + assertThat(result.membershipVersion()).isEqualTo(4L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(result.terminalProof().eventSequence()).isEqualTo(3L); + assertThat(result.terminalProof().auditEventId()) + .isNotNull() + .isNotEqualTo(first.auditEventId()); + assertThat(replay).isEqualTo(result); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(3L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(2L); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + assertThat(member.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(member.isGameplayAdmissionAllowed()).isTrue(); + } + + @Test + void restoreTerminalFailureRollsBackMemberRolesPairEventAndAudit() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + fixture.seedControlledInactiveOwnerSnapshot(); + String restoreRequest = fixture.prepareAnotherJoin(); + fixture.dsl.execute( + "CREATE FUNCTION fail_restore_terminal() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN IF NEW.status = 'COMMITTED' THEN RAISE EXCEPTION 'restore terminal failure'; " + + "END IF; RETURN NEW; END $$"); + fixture.dsl.execute( + "CREATE TRIGGER fail_restore_terminal BEFORE UPDATE ON account_join_operations " + + "FOR EACH ROW EXECUTE FUNCTION fail_restore_terminal()"); + + assertThatThrownBy(() -> fixture.commitExistingJoin(restoreRequest)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("restore terminal failure"); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + assertThat(member.getLifecycleState()).isEqualTo("INACTIVE"); + assertThat(member.getMembershipVersion()).isEqualTo(3L); + assertThat(member.getMembershipAuthorityGeneration()).isEqualTo(2L); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(2L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + var operation = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(restoreRequest) + .orElseThrow()); + assertThat(operation.status()).isEqualTo("PENDING"); + assertThat(operation.terminalProof()).isNull(); + } + + @Test + void browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommittedReceipt() { + Fixture fixture = newFixture(); + BrowserFacade browser = fixture.browserFacade(); + var realms = browser.service().listBootstrapRealms(browser.bootstrapToken(), "world"); + var selected = realms.getFirst(); + String requestId = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), requestId); + + var first = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + + assertThat(first.success()).isTrue(); + assertThat(first.outcomeCode()).isEqualTo("JOINED"); + assertThat(first.accountId()).isEqualTo(fixture.account.getAccountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(first.gameplayAdmissionAllowed()).isTrue(); + assertThat(first.replayed()).isFalse(); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + var stored = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow()); + assertThat(stored.status()).isEqualTo("COMMITTED"); + assertThat(stored.operationRepresentationVersion()).isEqualTo(2); + assertThat(stored.scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid); + } + + @Test + void directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwners() { + Fixture fixture = newFixture(); + BrowserFacade composed = fixture.browserFacade(); + var target = composed.target(); + String requestId = UUID.randomUUID().toString(); + var caller = + new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( + fixture.account.getAccountUuid(), + fixture.tenantUuid, + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + UUID.randomUUID().toString(), + requestId); + var selected = + new net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget( + fixture.tenantUuid, + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + var peer = + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + TEST_NAMESPACE + "/sa/game-session-service", + TEST_NAMESPACE, + "game-session-service"); + var context = + io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer); + context.run( + () -> { + var scope = composed.service().issueDirectTextConnectScope(caller, selected); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + scope.connectScopeId(), requestId); + var first = composed.service().joinPublicProductionFromGameSession(caller, request); + var replay = composed.service().joinPublicProductionFromGameSession(caller, request); + assertThat(first.success()).isTrue(); + assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.gameplayAdmissionAllowed()).isTrue(); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + }); + org.mockito.Mockito.verifyNoInteractions(composed.sessions()); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + private Fixture newFixture() { return new Fixture(newTestContext()); } @@ -408,7 +754,7 @@ private Account createAccount() { input.setUsername("canonical-join-" + suffix); input.setEmail("canonical-join-" + suffix + "@example.test"); input.setPasswordHash("integration-fixture-hash"); - input.setRole("player"); + // Player role belongs to the canonical tenant membership, not global Account authority. return inTransaction(() -> accounts.save(input)); } @@ -453,6 +799,11 @@ private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { private DemoTenantEntitlementRequest entitlementRequest( UUID requestId, DemoTenantEntitlementSnapshot current) { + return entitlementRequest(requestId, current, true); + } + + private DemoTenantEntitlementRequest entitlementRequest( + UUID requestId, DemoTenantEntitlementSnapshot current, boolean allowPublicJoin) { return new DemoTenantEntitlementRequest( requestId, tenantUuid, @@ -462,7 +813,7 @@ private DemoTenantEntitlementRequest entitlementRequest( current == null ? null : current.tenantAuthorityGeneration(), current == null ? null : current.tenantAuthoritySourceVersion(), true, - true, + allowPublicJoin, true, true, new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); @@ -491,6 +842,565 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoi () -> terminalCoordinator.commitCanonicalFirstJoin(scope, requestId, callerBinding)); } + private String prepareAnotherJoin() { + String nextRequest = UUID.randomUUID().toString(); + inTransaction( + () -> { + operations.lockAccount(account.getId()); + operations.insertCanonicalIntent(nextRequest, scope, callerBinding); + var policy = demoEntitlements.readCurrent(tenantUuid); + operations.bindCanonicalPolicyEvidence( + nextRequest, + scope, + callerBinding, + policy.allowPublicJoin(), + policy.entitlementVersion()); + return null; + }); + return nextRequest; + } + + private AccountJoinOperationRepository.CanonicalJoinOperationEvidence commitExistingJoin( + String nextRequest) { + return inTransaction( + () -> + terminalCoordinator.commitCanonicalJoin( + scope, nextRequest, callerBinding, null, null, null)); + } + + private BrowserFacade browserFacade() { + var jwt = + new net.firedevops.firemud.common.security.JwtUtil( + "controlled-browser-facade-integration-signing-key-0123456789", 300000L); + var sessions = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service.session.SessionService.class); + String bootstrap = + jwt.generateToken( + account.getAccountUuid().toString(), + 300000L, + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(sessions.isAccountSessionActive(account.getId(), bootstrap)) + .thenReturn(true); + var targets = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client + .CanonicalGameplayAdmissionDecisionReadClient.class); + var target = controlledPublishedTarget(); + org.mockito.Mockito.when( + targets.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = + new net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), TEST_NAMESPACE); + return net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, java.util.List.of(target))); + }); + org.mockito.Mockito.when( + targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class); + return net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target)); + }); + // The protected client is the controlled upstream boundary in this Account SQL composition; + // this fixture does not claim physical GS publication or World lifecycle validation. + org.mockito.Mockito.when( + targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + org.mockito.Mockito.when(published.selector()).thenReturn(selector); + org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); + return published; + }); + var hosting = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.class); + var observer = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.class); + var manager = Objects.requireNonNull(transaction.getTransactionManager()); + var clock = java.time.Clock.systemUTC(); + var properties = new net.firedevops.firemud.accountservice.config.AccountTokenProperties(); + properties.setConnectScopeExpirationMs(120000L); + var entitlementOwner = + new net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner( + tenantAuthorityEvents, + new net.firedevops.firemud.accountservice.service + .AccountHostingSubscriptionLifecycleService(hosting, observer, manager), + demoEntitlements, + manager, + clock); + var producerOwner = + new net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner( + new net.firedevops.firemud.accountservice.service.session + .AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions), + targets, + entitlementOwner, + accounts, + memberships, + freshTenants, + tenantAuthorityEvents, + connectScopes, + jwt, + properties, + clock, + manager, + TEST_NAMESPACE); + var service = + new net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + auditOutbox, + operations, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountEmailLoginChallengeRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository + .class), + memberships, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + new net.firedevops.firemud.accountservice.config.MailProperties(), + properties, + new net.firedevops.firemud.common.security.JwtAuthProperties(), + jwt, + sessions, + manager); + service.setCanonicalPublicRealmScopeOwner(producerOwner); + service.setCanonicalScopeConsumers( + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwt, connectScopes, manager, clock), + targets, + tenantAuthorityEvents, + demoEntitlements, + hosting, + observer, + terminalCoordinator, + TEST_NAMESPACE, + clock); + return new BrowserFacade(service, bootstrap, target, sessions); + } + + /** + * Protected GS transport remains a controlled owner response; Account SQL/JWT owners are real. + */ + private net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target + controlledPublishedTarget() { + UUID version = UUID.randomUUID(); + String digest = "a".repeat(64); + String initial = UUID.randomUUID().toString(); + var holdRequest = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request( + TEST_NAMESPACE, + tenantUuid, + scope.worldSlug(), + scope.realmId(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + version, + 1L, + initial, + digest, + net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold + .InitialAdmissionOrigin.NO_PRIOR_POINTER, + scope.catalogRevision(), + null); + var hold = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()); + return new net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target( + TEST_NAMESPACE, + "tenant", + tenantUuid, + scope.worldSlug(), + "World", + scope.realmId(), + scope.realmSlug(), + "Production", + 11L, + 44L, + scope.playableStateNamespaceId(), + "SHARED", + scope.gameInstanceId(), + version, + 1L, + scope.catalogRevision(), + scope.pointerVersion(), + digest, + 1L, + initial, + digest, + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + 1L, + "sha256:" + digest, + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .OwnerProofOutcome.COMMITTED, + false, + java.time.Instant.now(), + "PRESEEDED_ONLY"); + } + + /** Controlled retained INACTIVE input; this fixture does not claim a production leave owner. */ + private void seedControlledInactiveOwnerSnapshot() { + seedControlledMembershipSnapshot("INACTIVE", java.util.List.of("player")); + } + + /** Controlled owner snapshot; no leave, creator grant or lifecycle mutation API is claimed. */ + @SuppressWarnings("unchecked") + private void seedControlledMembershipSnapshot( + String lifecycle, java.util.List currentRoles) { + // The existing draft source-change owner requires a physical READ_COMMITTED connection. + var historicalTransaction = new TransactionTemplate(transaction.getTransactionManager()); + historicalTransaction.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + historicalTransaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + historicalTransaction.execute( + status -> { + operations.lockAccount(account.getId()); + var member = + memberships + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantUuid) + .orElseThrow(); + var generation = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + // This is controlled historical input, not an implemented leave/role-removal owner. + // One atomic invalidating transaction advances the closed Account source and fence; + // the member generation then advances under that same fence without inventing an + // Account event or weakening the V40 deferred source/fence checks. + var accountBefore = + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid()); + commitControlledClosedAccountSecurityChange(accountBefore.account()); + assertThat( + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ? " + + "AND generation = ? AND source_version = ?", + account.getAccountUuid(), + tenantUuid, + generation.generation(), + generation.sourceVersion())) + .isEqualTo(1); + var next = generations.read(generation.scope()); + var authority = + generations.readCompositeSnapshot( + ACCOUNT_ISSUER, + account.getAccountUuid(), + java.util.List.of(tenantUuid), + java.util.List.of(tenantUuid)); + var accountSource = + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid()); + assertThat(next.generation()).isEqualTo(generation.generation() + 1L); + assertThat(next.sourceVersion()).isEqualTo(generation.sourceVersion() + 1L); + assertThat(next.issuanceFence().value()) + .isEqualTo(generation.issuanceFence().value() + 1L); + assertThat(next.issuanceFence().sourceVersion()) + .isEqualTo(generation.issuanceFence().sourceVersion() + 1L); + assertThat(accountSource.issuanceFence()).isEqualTo(next.issuanceFence()); + assertThat(accountSource.account().generation()) + .isEqualTo(accountBefore.account().generation() + 1L); + assertThat(accountSource.account().sourceVersion()) + .isEqualTo(accountBefore.account().sourceVersion() + 1L); + assertThat(accountSource.account().checkpoint().sequence()) + .isEqualTo(accountBefore.account().checkpoint().sequence() + 1L); + var tenantSource = tenantAuthorityEvents.readCurrentByTenant(tenantUuid); + var prior = pairs.readForUpdate(account.getAccountUuid(), tenantUuid).orElseThrow(); + var previousEvent = + outbox.findEvent(membershipStream(), prior.eventSequence()).orElseThrow(); + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + Map event = + json.readValue( + new String(previousEvent.payload(), StandardCharsets.UTF_8), Map.class); + String inactiveRequest = "controlled-inactive-" + UUID.randomUUID(); + event.remove("eventDigest"); + event.put("eventId", UUID.randomUUID().toString()); + event.put("requestId", inactiveRequest); + event.put("outboxSequence", "2"); + event.put("membershipLifecycleState", lifecycle); + event.put("roles", currentRoles); + event.put("membershipVersion", Map.of(tenantUuid.toString(), "3")); + event.put("membershipAuthorityGeneration", Long.toString(next.generation())); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); + tuple.put( + "accountAuthorityGeneration", Long.toString(authority.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of( + tenantUuid.toString(), + Long.toString(authority.tenants().getFirst().generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantUuid.toString(), Long.toString(next.generation()))); + tuple.put("privateRealmGrantVersions", java.util.List.of()); + var cutoff = accountSource.account().accountSecurityCutoff().orElseThrow(); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence())); + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantUuid.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenantSource.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.toString(tenantSource.tenantBillingSequence()), + "outboxStreamKey", tenantSource.outboxStreamKey(), + "outboxSequence", Long.toString(tenantSource.outboxSequence())))); + event.put("authorityTuple", tuple); + event.put("issuanceFence", Long.toString(next.issuanceFence().value())); + event.put("gameplayAdmissionAllowed", false); + event.put("callerBoundAuthorityInvalidated", true); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + var appended = + outbox.append( + membershipStream(), + inactiveRequest, + sequence -> { + if (sequence != 2L) + throw new IllegalStateException("Controlled inactive sequence changed"); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = FALSE, " + + "membership_version = 3, membership_authority_generation = 2 WHERE id = ?", + lifecycle, + member.getId()); + var inactive = + memberships + .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantUuid) + .orElseThrow(); + roles.replaceCanonical( + inactive, account.getAccountUuid(), tenantUuid, provenance, 3L, currentRoles); + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = 3, membership_authority_generation = 2, " + + "last_event_sequence = 2, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + appended.eventId(), + appended.eventDigest(), + account.getAccountUuid(), + tenantUuid); + return null; + }); + } + + /** + * Controlled sole-writer composition of the existing closed security-state operation. The + * correlation bytes are fixture input, not authenticated permission or a runtime producer. Keep + * the source change, exact receipt, event and head in the enclosing historical transaction. + */ + private void commitControlledClosedAccountSecurityChange( + AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence currentSource) { + var current = accounts.findByIdForUpdate(account.getId()).orElseThrow(); + var roleSource = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ? FOR SHARE", + account.getAccountUuid())); + long roleVersion = + Objects.requireNonNull(roleSource.get("global_role_source_version", Long.class)); + var before = + new AccountState( + current.isEmailVerified(), + AccountLoginAuthModes.read(current.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleSource.get("global_roles", String[].class)) + .sorted() + .toList(), + current.getLifecycleState().name()); + var after = + new AccountState( + !before.emailVerified(), + before.loginAuthModes(), + before.globalRoles(), + before.lifecycleState()); + var sourceState = generations.read(currentSource.scope()); + String stream = currentSource.checkpoint().outboxStreamKey(); + long checkpointSequence = currentSource.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : outbox.findEvent(stream, checkpointSequence).orElseThrow().payload(); + UUID securityRequest = UUID.randomUUID(); + byte[] correlation = + ("{\"actorAccountUuid\":\"" + + account.getAccountUuid() + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + securityRequest + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + var request = + new AccountSecurityStateMutationRequest( + securityRequest, + account.getAccountUuid(), + correlation, + sourceState.generation(), + sourceState.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + var draft = + new Capture( + current.getId(), + current.getAccountUuidProvenance(), + before, + sourceState, + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(sourceState.generation()), + Long.toString(sourceState.sourceVersion()), + stream, + Long.toString(checkpointSequence), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), java.util.List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + sourceState, + checkpointSequence, + checkpointPayload, + roleVersion, + change); + var fences = new DraftAuthorizationFenceRepository(dsl); + var securityOperations = new AccountSecurityStateOperationRepository(dsl); + assertThat(fences.requestSourceChange(change)).isTrue(); + assertThat(securityOperations.claim(request, capture).claimed()).isTrue(); + assertThat(fences.sourceMutationPermitted(change)).isTrue(); + var advanced = + sourceEvidence.prepareClosedAccountAdvance(account.getAccountUuid(), currentSource); + assertThat( + dsl.execute( + "UPDATE accounts SET email_verified = ? WHERE account_uuid = ?", + after.emailVerified(), + account.getAccountUuid())) + .isEqualTo(1); + var event = + outbox.append( + stream, + securityRequest.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + securityRequest, + account.getAccountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + after)); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + var committed = securityOperations.complete(request, event, advanced, roleVersion); + assertThat(committed.receipt().orElseThrow().event()).isEqualTo(event); + assertThat(committed.capture().sourceChange().canonicalBytes()) + .isEqualTo(change.canonicalBytes()); + assertThat(fences.readSourceChange(change).status()).isEqualTo("SOURCE_COMMITTED"); + } + private long membershipId() { return membershipId == null ? -1L : membershipId; } @@ -574,4 +1484,12 @@ private static long positiveRandomLong() { } private record TestContext(DSLContext dsl, TransactionTemplate transaction) {} + + private record BrowserFacade( + net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl service, + String bootstrapToken, + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .Target + target, + net.firedevops.firemud.accountservice.service.session.SessionService sessions) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java new file mode 100644 index 0000000000..9df243230b --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -0,0 +1,389 @@ +package integration.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Physical Account transaction and real SDK decoding against a controlled local Stripe transport. + * Tenant/creator/billing setup and the caller/scope are controlled; no authenticated public caller, + * real Stripe, World hold, protected admission transport, custody or runtime activation is proved. + */ +class AccountPaidCanonicalFirstJoinPostgresIntegrationTest { + private static final String PREFIX = "paid_first_join_"; + private static final String CALLER = "controlled-paid-join-caller"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @AfterEach + void dropOwnedSchemas() { + var jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalStateException("Refusing unowned schema cleanup"); + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo() { + Context c = context(false); + int reads = c.hosting.transport().reads(); + var first = c.commit(c.observed); + var replay = c.commit(c.observed); + assertThat(replay).isEqualTo(first); + assertThat(c.hosting.transport().reads()).isEqualTo(reads); + assertThat(c.scope.accountId()).isNotEqualTo(c.hosting.accountUuid()); + var retained = + c.hosting.transaction().execute(status -> c.outbox.findEvent(c.stream(), 1L).orElseThrow()); + var event = + MembershipAuthorityEventV1Codec.verify( + new String(Objects.requireNonNull(retained).payload(), StandardCharsets.UTF_8)); + assertThat(event.accountId()).isEqualTo(c.scope.accountId().toString()); + assertThat(event.authorityTuple().tenantBillingCutoff()).isPresent(); + assertThat(event.authorityTuple().tenantAuthorityGeneration()) + .containsKey(c.hosting.tenantId().toString()); + assertThat(c.count("account_tenant_membership")).isEqualTo(1); + assertThat(c.count("account_tenant_membership_role_snapshots")).isEqualTo(1); + assertThat(c.count("account_audit_outbox")).isEqualTo(1); + assertThat(c.operation().status()).isEqualTo("COMMITTED"); + assertThat(c.operation().terminalProof()).isEqualTo(first); + } + + @Test + void providerFactsChangedBeforeCommitRollbackAllStagedWritesThenSameOriginalCanRecover() { + Context c = context(false); + var original = c.operation(); + c.hosting.providerStatus("canceled"); + var contradictory = c.hosting.observer().observe(c.fence.binding()); + assertThatThrownBy(() -> c.commit(contradictory)).isInstanceOf(IllegalStateException.class); + c.assertRolledBack(original); + c.hosting.providerStatus("active"); + var recovered = c.hosting.observer().observe(c.fence.binding()); + var committed = c.commit(recovered); + assertThat(committed.entitlementVersion()).isEqualTo(original.entitlementVersion()); + assertThat(c.count("account_tenant_membership")).isEqualTo(1); + assertThat(c.count("account_audit_outbox")).isEqualTo(1); + } + + @Test + void changedOperationPolicyCannotCommitAgainstAnOlderPaidReceipt() { + Context c = context(true); + var original = c.operation(); + assertThatThrownBy(() -> c.commit(c.observed)) + .hasMessageContaining("exact current public-join entitlement"); + c.assertRolledBack(original); + } + + @Test + void expiredPaidReceiptIsUnavailableAndNeverSelectsDemo() { + Context c = context(false); + var original = c.operation(); + c.hosting.clock().advance(Duration.ofHours(2)); + var freshSdkResult = c.hosting.observer().observe(c.fence.binding()); + assertThatThrownBy(() -> c.commit(freshSdkResult)).isInstanceOf(IllegalStateException.class); + c.assertRolledBack(original); + } + + @Test + void finalCommitFailureRollsBackMembershipRolesPairEventAuditAndTerminalReceipt() { + Context c = context(false); + var original = c.operation(); + assertThatThrownBy( + () -> + c.hosting + .transaction() + .execute( + status -> { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + throw new IllegalStateException( + "controlled final paid JOIN commit refusal"); + } + }); + return c.coordinator.commitPaidCanonicalFirstJoin( + c.scope, + c.requestId, + CALLER, + c.hosting.lifecycleRepository(), + c.fence, + c.observed); + })) + .hasMessageContaining("controlled final paid JOIN commit refusal"); + c.assertRolledBack(original); + } + + private Context context(boolean wrongPolicy) { + String schema = PREFIX + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var source = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new Context(CanonicalHostingSubscriptionTestFixture.create(source), wrongPolicy); + } + + private static final class Context { + private final CanonicalHostingSubscriptionTestFixture.Fixture hosting; + private final AccountJoinOperationRepository operations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountCanonicalFirstJoinTerminalCoordinator coordinator; + private final CanonicalJoinScopeV2 scope; + private final String requestId = UUID.randomUUID().toString(); + private final ReadFence fence; + private final StripeHostingSubscriptionObserver.Result observed; + + private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean wrongPolicy) { + this.hosting = hosting; + var claim = + hosting + .service() + .claimProvisioning(hosting.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + var committed = + hosting + .service() + .reconcile( + UUID.randomUUID(), + hosting.creation().requestId(), + claim.subscriptionRowVersion(), + hosting.providerId(), + claim.attemptId()); + assertThat(committed.outcome()) + .isEqualTo( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + hosting.transaction().setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var dsl = hosting.dsl(); + var accounts = new AccountRepository(dsl); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + pairs = new AccountMembershipPairAuthorityRepository(dsl); + var members = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(dsl, outbox, billing, fresh, generations); + var demos = + new AccountDemoTenantEntitlementRepository( + dsl, fresh, generations, billing, tenantEvents); + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), "prod"), + fresh); + operations = new AccountJoinOperationRepository(dsl, scopes); + var producer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + members, + roles, + generations, + outbox, + sources, + tenantEvents, + demos); + coordinator = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + operations, + members, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + producer); + Account input = new Account(); + input.setUsername("paid-player-" + UUID.randomUUID()); + input.setEmail("paid-player-" + UUID.randomUUID() + "@example.test"); + input.setPasswordHash("controlled-hash"); + input.setRole("player"); + Account player = + Objects.requireNonNull(hosting.transaction().execute(status -> accounts.save(input))); + var now = hosting.clock().instant(); + scope = + new CanonicalJoinScopeV2( + "controlled-paid-scope-" + UUID.randomUUID(), + player.getAccountUuid(), + hosting.tenantId(), + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + now.toString(), + now.plusSeconds(120).toString()); + hosting + .transaction() + .executeWithoutResult( + status -> { + var source = fresh.read(hosting.tenantId()).orElseThrow(); + sources.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + player.getAccountUuid(), hosting.tenantId())); + scopes.insertCanonical( + player.getId(), + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, CALLER); + }); + fence = + Objects.requireNonNull( + hosting + .transaction() + .execute( + status -> + hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); + observed = hosting.observer().observe(fence.binding()); + hosting + .transaction() + .executeWithoutResult( + status -> { + var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + CALLER, + receipt.allowPublicJoin(), + receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); + }); + } + + private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( + StripeHostingSubscriptionObserver.Result result) { + return Objects.requireNonNull( + hosting + .transaction() + .execute( + status -> + coordinator.commitPaidCanonicalFirstJoin( + scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); + } + + private AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation() { + return Objects.requireNonNull( + hosting + .transaction() + .execute( + status -> { + operations.lockAccount( + Objects.requireNonNull( + hosting + .dsl() + .fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ?", + scope.accountId())) + .get(0, Long.class)); + return operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + })); + } + + private String stream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId(); + } + + private int count(String table) { + return hosting.dsl().fetchCount(DSL.table(table)); + } + + private void assertRolledBack( + AccountJoinOperationRepository.CanonicalJoinOperationEvidence original) { + assertThat(operation()).isEqualTo(original); + assertThat(count("account_tenant_membership")).isZero(); + assertThat(count("account_tenant_membership_role_snapshots")).isZero(); + assertThat(count("account_audit_outbox")).isZero(); + var checkpoint = hosting.transaction().execute(status -> outbox.readCheckpoint(stream())); + assertThat(checkpoint).isEmpty(); + var pair = + hosting + .transaction() + .execute(status -> pairs.readForUpdate(scope.accountId(), scope.tenantId())); + assertThat(pair).isEmpty(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java new file mode 100644 index 0000000000..57cd9d560a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -0,0 +1,584 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical canonical Account/membership/scope/demo composition and lock/commit proof definitions. + * JWT/JWKS/Redis caller verification and current committed issuance are controlled doubles here; + * the protected GS/World client is also controlled. This does not prove custody, actual issuance, + * paid composition, mTLS or physical published routing. + */ +class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "player_entitlement_"; + private static final String NAMESPACE = "player-entitlement-proof"; + private static final String ISSUER = "firemud-account-service"; + private static final String PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing cleanup of an unowned schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { + Fixture f = fixture(false); + long before = f.dsl.fetchCount(DSL.table("account_tenant_membership")); + var value = f.owner.evaluate(f.request(), "controlled-token"); + assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); + assertThat(value.membershipSource().accountId()) + .isEqualTo(f.account.getAccountUuid().toString()); + assertThat(value.membershipSource().tenantId()).isEqualTo(f.tenantId.toString()); + assertThat(value.membershipSource().membershipExists()).isFalse(); + assertThat(value.membershipSource().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isFalse(); + assertThat(value.fields()).containsEntry("sourceKind", "NON_PAID_DEMO"); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))).isEqualTo(before); + var missing = + f.transaction.execute( + status -> f.memberships.findFreshMembership(f.account.getAccountUuid(), f.tenantId)); + assertThat(missing).isEmpty(); + assertThat(value.membershipSource().checkpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).contains("membership/"); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); + assertThat(value.membershipSource().sourceEvidence()).isNotEmpty(); + } + + @Test + void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { + Fixture f = fixture(true); + var value = f.owner.evaluate(f.request(), "controlled-token"); + assertThat(value.membershipSource().membershipExists()).isTrue(); + assertThat(value.membershipSource().membershipVersion()) + .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); + assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); + var binding = (Map) value.fields().get("target"); + assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); + assertThat(binding.get("playableStateNamespaceId")) + .isEqualTo(f.scope.playableStateNamespaceId().toString()); + assertThat(binding.get("gameInstanceId")).isEqualTo(f.scope.gameInstanceId().toString()); + assertThat(binding.get("catalogRevision")).isEqualTo("7"); + assertThat(binding.get("pointerVersion")).isEqualTo("3"); + assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), "controlled-token"); + } + + @Test + void captureHoldsActualAccountWriterLockAndFailureBeforeCommitExposesNoValue() { + Fixture f = fixture(false); + AtomicBoolean competingWriterRefused = new AtomicBoolean(); + doAnswer( + invocation -> { + Object snapshot = invocation.callRealMethod(); + try (Connection contender = f.dataSource.getConnection()) { + contender.setAutoCommit(false); + try (var statement = contender.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '150ms'"); + try (var select = + contender.prepareStatement( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + select.setObject(1, f.account.getAccountUuid()); + try { + select.executeQuery().close(); + throw new AssertionError( + "Account source lock did not exclude a competing writer"); + } catch (SQLException expectedLockTimeout) { + assertThat(expectedLockTimeout.getSQLState()).isEqualTo("55P03"); + competingWriterRefused.set(true); + } + } finally { + contender.rollback(); + } + } + } + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + throw new IllegalStateException("controlled final source commit refusal"); + } + }); + return snapshot; + }) + .when(f.demos) + .readCurrent(f.tenantId); + assertThatThrownBy(() -> f.owner.evaluate(f.request(), "controlled-token")) + .hasMessageContaining("controlled final source commit refusal"); + assertThat(competingWriterRefused.get()).isTrue(); + var unlocked = + f.transaction.execute( + status -> f.accounts.findByAccountUuidForUpdate(f.account.getAccountUuid())); + assertThat(unlocked).isPresent(); + } + + private Fixture fixture(boolean join) { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new Fixture(dataSource, join); + } + + /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ + private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { + when(targets.resolvePublishedRealmAdmissionTarget(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + .class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer( + readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return read; + }); + return resolved; + }); + } + + private static final class Fixture { + private final DriverManagerDataSource dataSource; + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final AccountRepository accounts; + private final AccountTenantMembershipRepository memberships; + private final AccountDemoTenantEntitlementRepository demos; + private final Account account; + private final UUID tenantId = UUID.randomUUID(); + private final CanonicalJoinScopeV2 scope; + private final AccountPlayerAdmissionEntitlementOwner owner; + + private Fixture(DriverManagerDataSource dataSource, boolean join) { + this.dataSource = dataSource; + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactions = new DataSourceTransactionManager(dataSource); + transaction = new TransactionTemplate(transactions); + accounts = new AccountRepository(dsl); + var tenants = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + memberships = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(dsl, outbox, billing, tenants, generations); + demos = + spy( + new AccountDemoTenantEntitlementRepository( + dsl, tenants, generations, billing, tenantEvents)); + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), NAMESPACE), + tenants); + var operations = new AccountJoinOperationRepository(dsl, scopes); + var membershipProducer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sources, + tenantEvents, + demos); + var terminal = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + operations, + memberships, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + membershipProducer); + var snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sources, + tenantEvents, + tenants, + memberships, + pairs, + roles, + outbox); + Account input = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + input.setUsername("player-" + suffix); + input.setEmail("player-entitlement-" + suffix + "@example.test"); + input.setPasswordHash("controlled-password-hash"); + // Gameplay player roles belong to the canonical tenant membership. + account = transaction.execute(status -> accounts.save(input)); + if (account == null) throw new IllegalStateException("Account insertion is absent"); + FreshTenantCreationEvidence tenantSource = tenantSource(tenantId); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantSource.operationId(), + tenantSource.evidenceDigest()); + scope = + new CanonicalJoinScopeV2( + "scope-" + UUID.randomUUID(), + account.getAccountUuid(), + tenantId, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + NOW.minusSeconds(20).toString(), + NOW.plusSeconds(120).toString()); + String joinRequestId = UUID.randomUUID().toString(); + String callerBinding = "controlled-join-caller"; + transaction.execute( + status -> { + tenants.importVerified(tenantSource); + sources.initializeIssuerIfAbsent(ISSUER); + generations.initializeTenantIfAbsent(tenantId); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + scopes.insertCanonical(account.getId(), scope, provenance); + operations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + return null; + }); + var entitlement = + transaction.execute( + status -> + demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + tenantSource.creationRequestId(), + tenantSource.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)), + tenantSource)); + if (entitlement == null) throw new IllegalStateException("Demo source is absent"); + transaction.execute( + status -> { + operations.bindCanonicalPolicyEvidence( + joinRequestId, + scope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + if (join) { + terminal.commitCanonicalFirstJoin(scope, joinRequestId, callerBinding); + } else { + accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); + memberships.prepareFreshCreatorAbsence(account.getAccountUuid(), tenantId); + } + return null; + }); + var issuances = mock(AccountGameplayDelegationIssuanceRepository.class); + var callers = mock(AccountGameplayAdmissionCallerVerifier.class); + var identity = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + account.getAccountUuid(), + PEER, + UUID.randomUUID(), + mock(AccountGameplayCredentialRequestBinding.class), + "a".repeat(64), + UUID.randomUUID(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond()); + var candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()) + .thenReturn( + new AccountAuthoritySnapshot( + account.getAccountUuid(), 1, 1, 1, 1, 1, 1, Optional.empty())); + when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); + when(candidate.signerCorrespondence()) + .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); + when(candidate.tokenSha256()).thenReturn("a".repeat(64)); + when(candidate.signerKid()).thenReturn("controlled-kid"); + when(candidate.signerGeneration()).thenReturn("1"); + when(candidate.canonicalRegistryRecordSha256()).thenReturn("b".repeat(64)); + when(candidate.commitProofSha256()).thenReturn("c".repeat(64)); + when(candidate.envelopeKeyId()).thenReturn("controlled-key"); + when(candidate.envelopeSha256()).thenReturn("d".repeat(64)); + var caller = mock(VerifiedCaller.class); + when(caller.identity()).thenReturn(identity); + when(caller.currentCandidate()).thenReturn(candidate); + when(callers.verifyPresentedCompactToken("controlled-token")).thenReturn(caller); + when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + dsl.connection( + connection -> + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + return Optional.of(candidate); + }); + var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + controlledTarget(targets); + owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + callers, + issuances, + snapshots, + scopes, + mock(AccountHostingSubscriptionLifecycleRepository.class), + mock(StripeHostingSubscriptionObserver.class), + demos, + tenantEvents, + targets, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + NAMESPACE); + } + + private Request request() { + return new Request( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + account.getAccountUuid(), + NAMESPACE, + tenantId, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()), + scope.connectScopeId(), + PEER); + } + } + + private static FreshTenantCreationEvidence tenantSource(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceKey = "w-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest(NAMESPACE, requestId, sourceKey, "World", null); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + 17, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + 17, + sourceKey, + "NEW_GAME_ROW")); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java index 5422151555..c17b6a2360 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.when; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Clock; @@ -22,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -32,6 +34,7 @@ import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; @@ -85,9 +88,11 @@ * Bootstrap JWT signing uses a local test key and the actual caller verifier/persisted Account; the * active-session registry and complete Game Session collection are controlled inputs. Fresh Game * Design evidence is imported as a fixture, not obtained from an authenticated owner call. The - * canonical public-scope cases additionally use real membership/pair and V2 scope persistence. This - * proves neither paid hosting, issuer custody, workload provenance, a World hold, private support - * nor gameplay admission; a retained selector is not PLAYER entitlement or JOIN permission. + * canonical public-scope cases additionally use real membership/pair, V2 scope persistence and + * retained-selector reads. Expected reader Account UUIDs are comparison inputs from this fixture, + * not caller authentication performed by the reader. This proves neither paid hosting, issuer + * custody, workload provenance, a World hold, private support nor gameplay admission; a retained + * selector is not PLAYER entitlement or JOIN permission. */ class AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest { private static final String NAMESPACE = "demo-worlds-proof"; @@ -350,6 +355,143 @@ void absentMembershipAndClosedEnrollmentPersistOnlyTheExactCanonicalPublicSelect .get(0, Long.class)) .isEqualTo(1L); f.assertNoMembershipPairJoinOrPaidReads(); + SessionContext.setContext( + f.account.getAccountUuid().toString(), + List.of("player"), + Map.of(tenant.tenantId().toString(), List.of("player"))); + + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + + assertThat(SessionContext.getAccountId()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(SessionContext.getScopedRoles(tenant.tenantId().toString())) + .containsExactly("player"); + assertThat(f.snapshot()).isEqualTo(after); + assertThat( + f.inTransaction( + () -> f.scopes.findCanonicalEvidenceByTokenHash(tokenHash).orElseThrow())) + .isEqualTo(evidence); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualRetainedScopeRefusesAnotherPersistedExpectedAccountWithoutChangingCallerContext() { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-wrong-account"); + Account other = new Account(); + other.setUsername("other-scope-reader"); + other.setEmail("other-scope-reader@example.test"); + other.setPasswordHash("controlled-unused-password-verifier"); + other.setRole("player"); + Account expected = f.inTransaction(() -> f.accounts.save(other)); + SessionContext.setContext(expected.getAccountUuid().toString(), List.of("player"), Map.of()); + Map before = f.snapshot(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.scopeReader.read(expected.getAccountUuid(), scope.connectScopeId())); + + assertThat(SessionContext.getAccountId()).isEqualTo(expected.getAccountUuid().toString()); + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + // The UUID argument is comparison data supplied by the outer owner; ambient roles/identity + // are neither accepted as source authority nor cleared to make this read succeed. + assertThat(SessionContext.getAccountId()).isEqualTo(expected.getAccountUuid().toString()); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualIssuedScopeExpiryRefusesWithoutRestampingItsRetainedSelector() { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-reader-expiry"); + Map before = f.snapshot(); + f.clock.offset.set( + Duration.between(f.clock.instant(), Instant.parse(scope.connectScopeExpiresAt())) + .plusSeconds(1)); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())); + + assertThat(f.snapshot()).isEqualTo(before); + assertThat(f.inTransaction(() -> f.scopes.findCanonical(scope.connectScopeId()).orElseThrow())) + .isEqualTo(scope); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualImmutableScopeGuardRejectsEvidenceMutationAndReaderReturnsOriginalPreimage() { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-immutable"); + Map before = f.snapshot(); + String tokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); + + org.jooq.exception.DataAccessException failure = + org.junit.jupiter.api.Assertions.assertThrows( + org.jooq.exception.DataAccessException.class, + () -> + f.dsl.execute( + "UPDATE account_connect_scope_records SET world_slug = ? WHERE scope_token_hash = ?", + "different-world", + tokenHash)); + + SQLException sql = Objects.requireNonNull(sqlFailure(failure)); + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains("Canonical Account connect scope evidence is immutable"); + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoMembershipPairJoinOrPaidReads(); + } + + @Test + void actualAccountLockTimeoutMakesScopeReadUnavailableAndFreshReadRecoversUnchanged() + throws SQLException { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-lock-timeout"); + Map before = f.snapshot(); + // Bound only this fixture DataSource's future physical connections. The reader still uses + // its real DataSourceTransactionManager, writable SERIALIZABLE transaction and repositories. + Properties connectionProperties = new Properties(); + connectionProperties.setProperty("connectTimeout", "10"); + connectionProperties.setProperty("socketTimeout", "60"); + connectionProperties.setProperty("options", "-c lock_timeout=150ms"); + f.dataSource.setConnectionProperties(connectionProperties); + try (Connection holder = f.dataSource.getConnection()) { + holder.setAutoCommit(false); + try { + try (var statement = + holder.prepareStatement("SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + statement.setObject(1, f.account.getAccountUuid()); + try (var locked = statement.executeQuery()) { + assertThat(locked.next()).isTrue(); + } + } + + AuthenticationException failure = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, + () -> f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())); + + assertThat(failure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + SQLException sql = Objects.requireNonNull(sqlFailure(failure)); + assertThat(sql.getSQLState()).isEqualTo("55P03"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } finally { + holder.rollback(); + } + } + + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoMembershipPairJoinOrPaidReads(); verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); } @@ -449,6 +591,7 @@ private static void assertCode(String code, Runnable operation) { } private static final class Fixture { + private final DriverManagerDataSource dataSource; private final DSLContext dsl; private final TransactionTemplate transaction; private final AccountRepository accounts; @@ -469,11 +612,13 @@ private static final class Fixture { private final String token; private final AccountPublicBootstrapWorldsOwner worlds; private final AccountCanonicalPublicRealmScopeOwner realmScopes; + private final AccountCanonicalConnectScopeReader scopeReader; private final AtomicInteger targetReadCount = new AtomicInteger(); private long sourceRowId; private Runnable onSecondTargetRead = () -> {}; private Fixture(DriverManagerDataSource dataSource) { + this.dataSource = dataSource; dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var transactions = new DataSourceTransactionManager(dataSource); transaction = new TransactionTemplate(transactions); @@ -520,6 +665,7 @@ private Fixture(DriverManagerDataSource dataSource) { dsl, new LegacyTenantSourceEvidence(dsl), NAMESPACE), NAMESPACE); scopes = new AccountConnectScopeRepository(dsl, retainedIdentities, tenants); + scopeReader = new AccountCanonicalConnectScopeReader(jwt, scopes, transactions, clock); var tokenProperties = new AccountTokenProperties(); tokenProperties.setConnectScopeExpirationMs(120000L); realmScopes = @@ -573,6 +719,15 @@ private FreshTenantCreationEvidence enrollTenant() { }); } + private CanonicalJoinScopeV2 issueScope(String worldSlug) { + DemoTenant tenant = demo(worldSlug, true); + targetReads(List.of(tenant.target()), List.of(tenant.target())); + return realmScopes + .listRealmScopes(token, tenant.target().tenantSlug(), tenant.target().worldSlug()) + .getFirst() + .scope(); + } + private DemoTenant demo(String worldSlug, boolean available) { FreshTenantCreationEvidence source = enrollTenant(); DemoTenantEntitlementSnapshot snapshot = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java new file mode 100644 index 0000000000..728fa4a612 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java @@ -0,0 +1,316 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Physical transport/projection proof only; published GS/World source facts are controlled inputs. + */ +class AccountBootstrapRosterReadClientMtlsTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID ACTOR = UUID.fromString("77777777-7777-4777-8777-777777777777"); + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Account bootstrap Entity read CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", false), + new IdentitySpec( + "entity", "spiffe://firemud/ns/test/sa/entity-management-service", true), + new IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/entity-management-service", true)); + } + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactEntityPeerPreservesRequestNamespaceAndActualLevelIncludingZero() throws Exception { + Probe service = new Probe(); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor().setLevel(0)) + .build(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + UUID requestId = UUID.randomUUID(); + var actors = client.read(requestId, ACCOUNT, published()); + assertThat(actors) + .containsExactly(new AccountBootstrapRosterReadClient.Actor(ACTOR, "Mara", 0)); + assertThat(service.request.get().getRequestUuid()).isEqualTo(requestId.toString()); + assertThat(service.request.get().getCanonicalAccountUuid()).isEqualTo(ACCOUNT.toString()); + assertThat(service.request.get().getExpectedTarget().getPlayableStateNamespaceUuid()) + .isEqualTo(NAMESPACE_ID.toString()); + assertThat(service.peer.get().isService("account-service")).isTrue(); + assertThat(service.peer.get().isInNamespace("test")).isTrue(); + service.respond = + request -> AccountBootstrapRosterReadResponse.newBuilder().setRequest(request).build(); + assertThat(client.read(UUID.randomUUID(), ACCOUNT, published())).isEmpty(); + } + } + + @Test + void localBrowserContextIsPreservedWithoutAnOutboundBearerCredential() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + SessionContext.setContext( + ACCOUNT.toString(), List.of("player"), Map.of(TENANT.toString(), List.of("tenantAdmin"))); + assertThat(client.read(UUID.randomUUID(), ACCOUNT, published())).isEmpty(); + assertThat(SessionContext.getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(SessionContext.getScopedRoles(TENANT.toString())).containsExactly("tenantAdmin"); + assertThat(service.authorization.get()).isNull(); + assertThat(service.peer.get().isService("account-service")).isTrue(); + } + } + + @Test + void foreignEntityIdentityIsRefusedBeforeApplicationDispatch() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + Probe service = new Probe(); + try (var server = server(identity, service); + var client = client(server.port())) { + client.init(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(service.calls.get()).isZero(); + } + } + } + + @Test + void mismatchedDuplicateAndMissingLevelResponsesNeverBecomeAnEmptySuccess() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request.toBuilder().setCanonicalAccountUuid(TENANT.toString())) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor()) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor().setLevel(2)) + .addActors(actor().setLevel(2)) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void ambientSqlRefusesBeforeTheEntityRead() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + assertThat(service.calls.get()).isZero(); + } + } + + private static AccountBootstrapRosterActor.Builder actor() { + return AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid(ACTOR.toString()) + .setDisplayName("Mara"); + } + + private static CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + published() { + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn("test"); + when(target.canonicalTenantId()).thenReturn(TENANT); + when(target.realmId()).thenReturn(REALM); + when(target.worldSlug()).thenReturn("world"); + when(target.realmSlug()).thenReturn("production"); + when(target.canonicalGameInstanceId()).thenReturn(INSTANCE); + when(target.canonicalVersionId()).thenReturn(VERSION); + when(target.playableStateNamespaceId()).thenReturn(NAMESPACE_ID); + when(target.playableStateScope()).thenReturn("SHARED"); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.catalogRevision()).thenReturn(1L); + when(target.pointerVersion()).thenReturn(1L); + when(target.activeWorldEpoch()).thenReturn(1L); + when(target.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + when(target.ownerProofDigest()).thenReturn("sha256:" + "b".repeat(64)); + var policy = mock(PublishedRealmEntryPolicyEvidence.class); + when(policy.policyDigest()).thenReturn("sha256:" + "c".repeat(64)); + var policySet = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policySet.publishedReleaseBundleRef()).thenReturn("controlled-release"); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.selectedPolicyEvidence()).thenReturn(policy); + when(source.publishedPolicySetEvidence()).thenReturn(policySet); + var result = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(result.currentTarget()).thenReturn(target); + when(result.sourceEvidence()).thenReturn(source); + when(result.selector()) + .thenReturn( + new CanonicalGameplayRosterOwnerReadEvidence.Request( + UUID.randomUUID(), + ACCOUNT, + "test", + TENANT, + "world", + REALM, + "production", + NAMESPACE_ID, + "SHARED", + INSTANCE, + VERSION, + 1L, + 1L, + 1L)); + return result; + } + + private static AccountBootstrapRosterReadClient client(int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("127.0.0.1:" + port); + return new AccountBootstrapRosterReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("account")), + new GrpcChannelFactory(), + "test"); + } + + private static Loopback server(String alias, Probe service) throws Exception { + var identity = pki.identity(alias); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + new GrpcPeerIdentityInterceptor(), + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + service.authorization.set( + headers.get( + io.grpc.Metadata.Key.of( + "authorization", io.grpc.Metadata.ASCII_STRING_MARSHALLER))); + return next.startCall(call, headers); + } + })) + .build() + .start(); + return new Loopback(server); + } + + private record Loopback(Server server) implements AutoCloseable { + int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2L, TimeUnit.SECONDS)) + throw new IllegalStateException("Entity discovery fixture did not terminate"); + } + } + + private static final class Probe + extends AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceImplBase { + final AtomicInteger calls = new AtomicInteger(); + final AtomicReference request = new AtomicReference<>(); + final AtomicReference peer = new AtomicReference<>(); + final AtomicReference authorization = new AtomicReference<>(); + Function respond = + value -> AccountBootstrapRosterReadResponse.newBuilder().setRequest(value).build(); + + @Override + public void readAccountBootstrapRoster( + AccountBootstrapRosterReadRequest value, + StreamObserver observer) { + calls.incrementAndGet(); + request.set(value); + peer.set(GrpcPeerIdentity.current()); + assertThat(Context.current().getDeadline()).isNotNull(); + observer.onNext(respond.apply(value)); + observer.onCompleted(); + } + } +} 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 609772d54f..1d9ab6e91e 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 @@ -17,6 +17,7 @@ import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -62,7 +63,44 @@ void localJoinResponseCarriesAccountUuidWithoutPublishingTheRoute() throws Excep when(accountService.joinPublicProduction("bootstrap", request)) .thenReturn( new net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult( - true, "JOINED", accountUuid, 7L, 8L, 1L, 1L, false)); + true, + "JOINED", + accountUuid, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 8L, + 2L, + 1L, + true, + false)); + mockMvc + .perform( + post("/auth/bootstrap/join") + .header(HttpHeaders.AUTHORIZATION, "Bearer bootstrap") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.accountId").value(accountUuid)) + .andExpect(jsonPath("$.data.gameplayAdmissionAllowed").value(true)); + } + + @Test + void successfulActiveMembershipResponsePreservesNonAdmittingSnapshot() throws Exception { + String account = "d09f80cb-a46a-415e-8d35-c9e8068e49de"; + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + "scope", "active-request"); + when(accountService.joinPublicProduction("bootstrap", request)) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult( + true, + "ALREADY_ACTIVE", + account, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 8L, + 3L, + 2L, + false, + false)); mockMvc .perform( post("/auth/bootstrap/join") @@ -70,7 +108,9 @@ void localJoinResponseCarriesAccountUuidWithoutPublishingTheRoute() throws Excep .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.accountId").value(accountUuid)); + .andExpect(jsonPath("$.data.success").value(true)) + .andExpect(jsonPath("$.data.outcomeCode").value("ALREADY_ACTIVE")) + .andExpect(jsonPath("$.data.gameplayAdmissionAllowed").value(false)); } @Test @@ -239,17 +279,16 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { new BootstrapRealmDto( "demo", "production", - "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"), "Live Realm", - 1L, - 42L, + UUID.fromString("07aee9f3-a635-4b7f-aa66-86489320d7c3"), + UUID.fromString("3ddc3564-435b-479d-b14d-c91995e673cc"), 17L, 23L, - "8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88", + UUID.fromString("8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88"), "PLAYABLE_STATE_SCOPE_SHARED", - false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", "2026-03-30T00:00:00Z", "2026-03-30T00:02:00Z", "scope-1"))); @@ -262,6 +301,10 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data[0].realmSlug").value("production")) .andExpect(jsonPath("$.data[0].realmId").value("4c4b57d8-e3a2-48fe-9977-e7df0fdce901")) + .andExpect(jsonPath("$.data[0].tenantId").value("07aee9f3-a635-4b7f-aa66-86489320d7c3")) + .andExpect( + jsonPath("$.data[0].gameInstanceId").value("3ddc3564-435b-479d-b14d-c91995e673cc")) + .andExpect(jsonPath("$.data[0].requiresCharacterSelection").doesNotExist()) .andExpect(jsonPath("$.data[0].catalogRevision").value(23)) .andExpect( jsonPath("$.data[0].playableStateNamespaceId") @@ -275,7 +318,13 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { void listBootstrapCharactersReturnsCharacters() throws Exception { when(accountService.listBootstrapCharacters("boot123", "demo", "production", "scope-1")) .thenReturn( - List.of(new BootstrapCharacterDto("char-1", "Mara", 12, "SHARED", "ALLOW_NEW"))); + List.of( + new BootstrapCharacterDto( + "11111111-1111-4111-8111-111111111111", + "Mara", + 12, + "SHARED", + "PRESEEDED_ONLY"))); mockMvc .perform( @@ -284,8 +333,11 @@ void listBootstrapCharactersReturnsCharacters() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data[0].characterId").value("char-1")) - .andExpect(jsonPath("$.data[0].characterName").value("Mara")); + .andExpect(jsonPath("$.data[0].characterId").value("11111111-1111-4111-8111-111111111111")) + .andExpect(jsonPath("$.data[0].characterName").value("Mara")) + .andExpect(jsonPath("$.data[0].level").value(12)) + .andExpect(jsonPath("$.data[0].stateScope").value("SHARED")) + .andExpect(jsonPath("$.data[0].characterCreationPolicy").value("PRESEEDED_ONLY")); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java index 0ee7acf515..92cd994074 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.dto; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -75,6 +76,14 @@ void preservesExactSelectorAndUtcTimestampBytesInDigestInput() { assertNotEquals(AccountJoinDigest.scopeV2(scope), AccountJoinDigest.scopeV2(alternateSelector)); } + @Test + void redactsBearerFromDiagnosticStringWithoutChangingItsWireAccessor() { + CanonicalJoinScopeV2 scope = scope(); + + assertEquals("connect-scope-42", scope.connectScopeId()); + assertThat(scope.toString()).contains("").doesNotContain(scope.connectScopeId()); + } + private static Class componentType(RecordComponent[] components, String name) { return Arrays.stream(components) .filter(component -> component.getName().equals(name)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java index 13ca149b90..acfc3ea06e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -5,7 +5,13 @@ import java.time.Instant; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import org.junit.jupiter.api.Test; class AccountJoinOperationRepositoryCanonicalTest { @@ -26,39 +32,161 @@ void terminalProofBindsFirstSequenceAndExactMembershipRevision() { } @Test - void terminalProofRejectsNonFirstSequenceAndUnsupportedMembershipRevision() { + void terminalProofRetainsLaterMembershipEventAndRevisionWithoutClaimingFirstJoin() { + var later = proof(3L, 4L); + assertThat(later.eventSequence()).isEqualTo(3L); + assertThat(later.membershipVersion()).isEqualTo(4L); + // Actual first-JOIN writes retain their distinct exact 1/2/1 repository and SQL checks. + } + + @Test + void terminalProofRejectsNonpositiveEventOrMembershipRevision() { + assertThatThrownBy(() -> proof(0L, 2L)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> proof(1L, 0L)).isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalJoinTerminalProof proof(long sequence, long version) { + return new CanonicalJoinTerminalProof( + STREAM, + sequence, + "event-1", + SHA256, + UUID.fromString("75c70a9e-beb4-3ee2-9d9d-50e28f1123d6"), + SHA256, + Instant.parse("2026-10-04T00:00:00Z"), + 5L, + 73L, + version, + 1L); + } + + @Test + void boundPendingDiagnosticsRemainSeparateFromTheAvailablePolicy() { + var unavailable = + evidence(true, "PENDING", null, "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", null, null); + assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(unavailable.entitlementVersion()).isEqualTo(5); + assertThat(unavailable.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> evidence(true, "PENDING", null, "UNAVAILABLE", null, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + evidence(true, "PENDING", null, "AVAILABLE", "ENTITLEMENT_UNAVAILABLE", null, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void failedEvidenceMayRetainPolicyButCannotCarrySuccessProofOrRetryableOutcome() { + var prePolicy = + evidence(false, "FAILED", "CONNECT_SCOPE_INVALID", "NOT_EVALUATED", null, null, null); + var afterPolicy = + evidence(true, "FAILED", "IDEMPOTENCY_CONFLICT", "AVAILABLE", null, null, null); + assertThat(prePolicy.requestDigest()).isNull(); + assertThat(afterPolicy.entitlementVersion()).isEqualTo(5); + assertThat(afterPolicy.membershipId()).isNull(); + assertThat(afterPolicy.terminalProof()).isNull(); + assertThatThrownBy( + () -> evidence(true, "FAILED", "AUTH_UNAVAILABLE", "AVAILABLE", null, null, null)) + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> - new CanonicalJoinTerminalProof( - STREAM, - 2L, - "event-1", - SHA256, - UUID.fromString("75c70a9e-beb4-3ee2-9d9d-50e28f1123d6"), - SHA256, - Instant.parse("2026-10-04T00:00:00Z"), - 5L, - 73L, - 2L, - 1L)) + evidence( + true, "FAILED", "CONNECT_SCOPE_INVALID", "AVAILABLE", null, validProof(), 73L)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> - new CanonicalJoinTerminalProof( - STREAM, - 1L, - "event-1", - SHA256, - UUID.fromString("75c70a9e-beb4-3ee2-9d9d-50e28f1123d6"), - SHA256, - Instant.parse("2026-10-04T00:00:00Z"), - 5L, - 73L, - 3L, - 1L)) + evidence( + true, + "FAILED", + "CONNECT_SCOPE_INVALID", + "UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + null, + null)) .isInstanceOf(IllegalArgumentException.class); } + /** Controlled journal content, not caller authentication or entitlement source evidence. */ + private static CanonicalJoinOperationEvidence evidence( + boolean bound, + String status, + String outcome, + String attemptAvailability, + String attemptFailure, + CanonicalJoinTerminalProof proof, + Long membershipId) { + UUID account = UUID.fromString("f4df3b0a-5fc6-4f86-9efc-0f053103b200"); + UUID tenant = UUID.fromString("4347218b-6914-4d50-a5ce-1b4836034f45"); + UUID realm = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var scope = + new CanonicalJoinScopeV2( + "controlled-canonical-scope", + account, + tenant, + realm, + "tenant", + "world", + "production", + realm, + "SHARED", + realm, + 7, + 3, + "2026-11-02T00:00:00Z", + "2026-11-02T00:02:00Z"); + var retained = + new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + 17, + "PUBLIC_PRODUCTION", + account, + tenant, + realm, + "tenant", + "world", + "production", + realm, + "SHARED", + realm, + 7, + 3, + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + 2, + AccountJoinDigest.scopeV2(scope), + new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, realm, SHA256)); + return new CanonicalJoinOperationEvidence( + "request-1", + 17, + "caller-1", + retained.scopeTokenHash(), + retained.scopeDigest(), + 2, + 2, + 2, + AccountJoinDigest.intentV2("request-1", scope, "caller-1"), + bound ? "AVAILABLE" : "NOT_EVALUATED", + bound ? true : null, + bound ? 5L : null, + bound ? 2 : null, + bound + ? AccountJoinDigest.requestV2( + scope, "caller-1", AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, true, 5L) + : null, + attemptAvailability, + attemptFailure, + false, + status, + outcome, + membershipId, + null, + null, + proof, + retained); + } + private static CanonicalJoinTerminalProof validProof() { return new CanonicalJoinTerminalProof( STREAM, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java index 73ebf73ad8..33c03fd2ca 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java @@ -270,6 +270,48 @@ baseline, new PairTransition(true, 2L, EVENT_ID_TEXT, EVENT_DIGEST, false))) verifyNoInteractions(dsl); } + @Test + void restoreCannotReuseAbsenceOrInventAnAuthorityInvalidation() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipPairAuthorityRepository repository = + new AccountMembershipPairAuthorityRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + PairAuthority absence = + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); + assertThatThrownBy( + () -> + repository.commitRestore( + absence, new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current positive pair"); + PairAuthority positive = + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 3L, + 2L, + 2L, + "inactive-event", + EVENT_DIGEST, + true); + assertThatThrownBy( + () -> + repository.commitRestore( + positive, new PairTransition(true, 3L, EVENT_ID_TEXT, EVENT_DIGEST, true))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current positive pair"); + assertThatThrownBy( + () -> + repository.commitRestore( + positive, new PairTransition(true, 4L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current positive pair"); + verifyNoInteractions(dsl); + } + private static VerifiedTenantProvenance freshProvenance() { return new VerifiedTenantProvenance( null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, DIGEST); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java new file mode 100644 index 0000000000..6a57f07a05 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountPlayerAdmissionEntitlementWorkloadGuardTest { + private final AccountPlayerAdmissionEntitlementWorkloadGuard guard = + new AccountPlayerAdmissionEntitlementWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { + var method = + AccountPlayerAdmissionEntitlementReadServiceGrpc.getReadPlayerAdmissionEntitlementMethod(); + assertThat(invoke(method, tls("firemud", "game-session-service"))).isNull(); + assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("firemud", "account-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invoke(AccountServiceGrpc.getGetProfileMethod(), tls("firemud", "game-session-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = + AccountPlayerAdmissionEntitlementReadServiceGrpc.getReadPlayerAdmissionEntitlementMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Status invoke(MethodDescriptor method, SSLSession ssl) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method); + when(call.getAttributes()) + .thenReturn( + ssl == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignored, headers) -> { + assertThat(guard.requireAuthenticatedGameSessionCaller()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/game-session-service"); + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + guard.interceptCall(call, new Metadata(), next); + var captured = ArgumentCaptor.forClass(Status.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + return captured.getAllValues().isEmpty() ? null : captured.getValue(); + } + + private static SSLSession tls(String namespace, String service) throws Exception { + var leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + var ssl = mock(SSLSession.class); + when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return ssl; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java new file mode 100644 index 0000000000..611243e7a8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java @@ -0,0 +1,490 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.jsonwebtoken.Claims; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountCanonicalConnectScopeReaderTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID GAME_INSTANCE = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String SECRET = "controlled-account-canonical-connect-scope-key-0123456789"; + private static final String PROVENANCE_DIGEST = "sha256:" + "a".repeat(64); + private static final long TOKEN_LIFETIME_MILLIS = 300_000L; + + @AfterEach + void clearThreadContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void returnsExactSignedV2SelectorOnlyAfterMatchingAccountHashAndProvenanceReadback() { + Fixture f = new Fixture(); + SessionContext.setContext( + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + List.of("tenantAdmin"), + Map.of(TENANT.toString(), List.of("tenantAdmin"))); + String originalSessionAccount = SessionContext.getAccountId(); + + CanonicalJoinScopeV2 actual = f.reader.read(ACCOUNT, f.scope.connectScopeId()); + + assertThat(actual).isEqualTo(f.scope); + assertThat(f.clock.instant()).isAfter(Instant.parse(f.scope.evaluatedAt())); + assertThat(f.jwt.parseToken(f.scope.connectScopeId()).getPayload().getIssuedAt().toInstant()) + .isAfter(Instant.parse(f.scope.evaluatedAt())); + assertThat(SessionContext.getAccountId()).isEqualTo(originalSessionAccount); + assertThat(SessionContext.getScopedRoles(TENANT.toString())).containsExactly("tenantAdmin"); + assertThat(f.transactions.started).isEqualTo(1); + assertThat(f.transactions.commits).isEqualTo(1); + assertThat(f.transactions.rollbacks).isZero(); + verify(f.scopes).findCanonical(f.scope.connectScopeId()); + verify(f.scopes) + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + } + + @Test + void refusesWrongExpectedUuidBeforeReadingAccountStorage() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), f.scope.connectScopeId())); + + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void refusesMissingOrMalformedSignedProfileBeforeAccountRead() { + Fixture f = new Fixture(); + + assertCode("CONNECT_SCOPE_INVALID", () -> f.reader.read(ACCOUNT, "not-a-jwt")); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("aud", "player-bootstrap")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue( + claims -> + claims.put( + "aud", List.of("bootstrap-connect-scope", "player-bootstrap"))))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("targetClass", "PRIVATE")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("scopeDigestVersion", 1L)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("accountId", "123")))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void rejectsNumericTenantFallbackAndNoncanonicalOrNilUuidClaims() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("tenantId", 42L)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue(claims -> claims.put("tenantId", "22222222-2222-4222-8222-22222222222")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue(claims -> claims.put("realmId", "00000000-0000-0000-0000-000000000000")))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void rejectsInvalidRuntimeSelectorsAndNoncanonicalTimeClaims() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("catalogRevision", 0L)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("pointerVersion", "9")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read(ACCOUNT, f.issue(claims -> claims.put("playableStateScope", "shared")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue(claims -> claims.put("evaluatedAt", "2026-10-03T01:02:03+00:00")))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void rejectsFutureEvaluationExpiredScopeAndJwtExpiryContradiction() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue( + claims -> + claims.put("evaluatedAt", Instant.now().plusSeconds(30).toString())))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + new AccountCanonicalConnectScopeReader( + f.jwt, + f.scopes, + new RecordingTransactions(), + Clock.offset(f.clock, Duration.ofMinutes(6))) + .read(ACCOUNT, f.scope.connectScopeId())); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue( + claims -> + claims.put( + "connectScopeExpiresAt", + Instant.parse((String) claims.get("connectScopeExpiresAt")) + .plusSeconds(1) + .toString())))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void refusesAbsentScopeAndMismatchWithImmutablePersistedV2Evidence() { + Fixture f = new Fixture(); + when(f.scopes.findCanonical(f.scope.connectScopeId())).thenReturn(Optional.empty()); + assertCode("CONNECT_SCOPE_INVALID", () -> f.reader.read(ACCOUNT, f.scope.connectScopeId())); + assertThat(f.transactions.rollbacks).isEqualTo(1); + + Fixture changed = new Fixture(); + CanonicalJoinScopeV2 different = changed.copyWithWorldSlug("other-world"); + when(changed.scopes.findCanonical(changed.scope.connectScopeId())) + .thenReturn(Optional.of(different)); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> changed.reader.read(ACCOUNT, changed.scope.connectScopeId())); + assertThat(changed.transactions.rollbacks).isEqualTo(1); + + Fixture wrongDigest = new Fixture(); + CanonicalConnectScopeEvidence validEvidence = evidence(wrongDigest.scope); + when(wrongDigest.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(wrongDigest.scope.connectScopeId()))) + .thenReturn(Optional.of(withDigest(validEvidence, "sha256:" + "b".repeat(64)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> wrongDigest.reader.read(ACCOUNT, wrongDigest.scope.connectScopeId())); + assertThat(wrongDigest.transactions.rollbacks).isEqualTo(1); + } + + @Test + void mapsDatabaseFailureAndCommitFailureToSafeAuthorityUnavailable() { + Fixture readFailure = new Fixture(); + when(readFailure.scopes.findCanonical(readFailure.scope.connectScopeId())) + .thenThrow(new org.jooq.exception.DataAccessException("controlled storage failure")); + assertCode( + "AUTH_UNAVAILABLE", + () -> readFailure.reader.read(ACCOUNT, readFailure.scope.connectScopeId())); + assertThat(readFailure.transactions.rollbacks).isEqualTo(1); + + Fixture commitFailure = new Fixture(); + commitFailure.transactions.failCommit = true; + assertCode( + "AUTH_UNAVAILABLE", + () -> commitFailure.reader.read(ACCOUNT, commitFailure.scope.connectScopeId())); + + Fixture rollbackFailure = new Fixture(); + when(rollbackFailure.scopes.findCanonical(rollbackFailure.scope.connectScopeId())) + .thenReturn(Optional.empty()); + rollbackFailure.transactions.failRollback = true; + assertCode( + "AUTH_UNAVAILABLE", + () -> rollbackFailure.reader.read(ACCOUNT, rollbackFailure.scope.connectScopeId())); + } + + @Test + void refusesAmbientTransactionWithoutChangingCallerSessionContext() { + Fixture f = new Fixture(); + SessionContext.setContext(ACCOUNT.toString(), List.of("player"), Map.of()); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> f.reader.read(ACCOUNT, f.scope.connectScopeId())) + .isInstanceOf(IllegalStateException.class); + + assertThat(SessionContext.getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + private static void assertCode(String expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> { + AuthenticationException authentication = (AuthenticationException) failure; + assertThat(authentication.getCode()).isEqualTo(expected); + assertThat(authentication.getMessage()).doesNotContain("eyJ"); + }); + } + + private static CanonicalJoinScopeV2 scope(String token, String evaluatedAt, String expiresAt) { + return new CanonicalJoinScopeV2( + token, + ACCOUNT, + TENANT, + REALM, + "acme-worlds", + "demo", + "main", + NAMESPACE, + "SHARED", + GAME_INSTANCE, + 9L, + 13L, + evaluatedAt, + expiresAt); + } + + private static CanonicalJoinScopeV2 copyWithWorldSlug( + CanonicalJoinScopeV2 original, String world) { + return new CanonicalJoinScopeV2( + original.connectScopeId(), + original.accountId(), + original.tenantId(), + original.realmId(), + original.tenantSlug(), + world, + original.realmSlug(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.gameInstanceId(), + original.catalogRevision(), + original.pointerVersion(), + original.evaluatedAt(), + original.connectScopeExpiresAt()); + } + + private static final class Fixture { + private final Clock clock; + private final JwtUtil jwt = new JwtUtil(SECRET, TOKEN_LIFETIME_MILLIS); + private final AccountConnectScopeRepository scopes = + Mockito.mock(AccountConnectScopeRepository.class); + private final RecordingTransactions transactions = new RecordingTransactions(); + private final AccountCanonicalConnectScopeReader reader; + private final CanonicalJoinScopeV2 scope; + + private Fixture() { + Token token = AccountCanonicalConnectScopeReaderTest.issue(jwt, claims -> {}); + Claims claims = jwt.parseToken(token.value()).getPayload(); + String expiresAt = claims.get("connectScopeExpiresAt", String.class); + clock = + Clock.fixed( + Instant.parse(claims.get("evaluatedAt", String.class)).plusSeconds(1), + ZoneOffset.UTC); + scope = scope(token.value(), claims.get("evaluatedAt", String.class), expiresAt); + when(scopes.findCanonical(token.value())).thenReturn(Optional.of(scope)); + when(scopes.findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(token.value()))) + .thenReturn(Optional.of(evidence(scope))); + reader = new AccountCanonicalConnectScopeReader(jwt, scopes, transactions, clock); + } + + private String issue(Consumer> mutation) { + return AccountCanonicalConnectScopeReaderTest.issue(jwt, mutation).value(); + } + + private CanonicalJoinScopeV2 copyWithWorldSlug(String world) { + return AccountCanonicalConnectScopeReaderTest.copyWithWorldSlug(scope, world); + } + } + + private static Token issue(JwtUtil jwt, Consumer> mutation) { + for (int attempt = 0; attempt < 100; attempt++) { + long before = System.currentTimeMillis(); + Instant expiresAt = + Instant.ofEpochMilli(before) + .truncatedTo(ChronoUnit.SECONDS) + .plusMillis(TOKEN_LIFETIME_MILLIS); + Map claims = new LinkedHashMap<>(); + claims.put("aud", "bootstrap-connect-scope"); + claims.put("accountId", ACCOUNT.toString()); + claims.put("targetClass", "PUBLIC_PRODUCTION"); + claims.put("scopeDigestVersion", 2L); + claims.put("tenantId", TENANT.toString()); + claims.put("tenantSlug", "acme-worlds"); + claims.put("worldSlug", "demo"); + claims.put("realmId", REALM.toString()); + claims.put("realmSlug", "main"); + claims.put("playableStateNamespaceId", NAMESPACE.toString()); + claims.put("playableStateScope", "SHARED"); + claims.put("gameInstanceId", GAME_INSTANCE.toString()); + claims.put("catalogRevision", 9L); + claims.put("pointerVersion", 13L); + claims.put("evaluatedAt", Instant.ofEpochMilli(before - 2_000L).toString()); + claims.put("connectScopeExpiresAt", expiresAt.toString()); + claims.put("jti", UUID.randomUUID().toString()); + mutation.accept(claims); + String value = + jwt.generateToken( + ACCOUNT.toString(), expiresAt.toEpochMilli() - System.currentTimeMillis(), claims); + Instant actualExpiry = jwt.parseToken(value).getPayload().getExpiration().toInstant(); + if (expiresAt.equals(actualExpiry)) return new Token(value); + } + throw new IllegalStateException("Could not create exact test JWT expiry"); + } + + private static CanonicalConnectScopeEvidence evidence(CanonicalJoinScopeV2 scope) { + return new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + 41L, + "PUBLIC_PRODUCTION", + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + 2, + AccountJoinDigest.scopeV2(scope), + new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION, PROVENANCE_DIGEST)); + } + + private static CanonicalConnectScopeEvidence withDigest( + CanonicalConnectScopeEvidence evidence, String digest) { + return new CanonicalConnectScopeEvidence( + evidence.scopeTokenHash(), + evidence.privateAccountId(), + evidence.targetClass(), + evidence.accountUuid(), + evidence.tenantUuid(), + evidence.realmId(), + evidence.tenantSlug(), + evidence.worldSlug(), + evidence.realmSlug(), + evidence.playableStateNamespaceUuid(), + evidence.playableStateScope(), + evidence.gameInstanceUuid(), + evidence.catalogRevision(), + evidence.pointerVersion(), + evidence.evaluatedAt(), + evidence.connectScopeExpiresAt(), + evidence.scopeDigestVersion(), + digest, + evidence.tenantProvenance()); + } + + private record Token(String value) {} + + private static final class RecordingTransactions implements PlatformTransactionManager { + private int started; + private int commits; + private int rollbacks; + private boolean failCommit; + private boolean failRollback; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition actual = + definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(actual.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(actual.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(actual.getTimeout()).isEqualTo(5); + assertThat(actual.isReadOnly()).isFalse(); + started++; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + try { + if (failCommit) throw new IllegalStateException("controlled commit failure"); + commits++; + } finally { + clearTransaction(); + } + } + + @Override + public void rollback(TransactionStatus status) { + rollbacks++; + try { + if (failRollback) throw new IllegalStateException("controlled rollback failure"); + } finally { + clearTransaction(); + } + } + + private static void clearTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index 636c33e740..f42e935ed9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; @@ -32,6 +33,8 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -75,14 +78,25 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } - @Test - void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangePending(); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(fixture.eventProducer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) + .thenReturn(fixture.checkpoint); CanonicalJoinTerminalProof result = - fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.coordinator.commitPaidCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed) + : fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING); assertThat(result).isEqualTo(fixture.expectedProof); InOrder ordered = inOrder(fixture.memberships, fixture.roles, fixture.eventProducer); @@ -91,9 +105,15 @@ void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { .verify(fixture.roles) .replaceCanonical( fixture.membership, ACCOUNT_ID, TENANT_ID, fixture.provenance, 2L, List.of("player")); - ordered - .verify(fixture.eventProducer) - .publishCanonicalFirstJoinMembershipChange(fixture.scope, REQUEST_ID, CALLER_BINDING); + if (paid) + ordered + .verify(fixture.eventProducer) + .publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed); + else + ordered + .verify(fixture.eventProducer) + .publishCanonicalFirstJoinMembershipChange(fixture.scope, REQUEST_ID, CALLER_BINDING); verify(fixture.audit) .appendCanonicalTenant( fixture.expectedProof.auditEventId(), @@ -104,14 +124,25 @@ void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { .commitCanonicalFirstJoin(REQUEST_ID, fixture.scope, CALLER_BINDING, fixture.expectedProof); } - @Test - void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangeCommittedReplay(); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); CanonicalJoinTerminalProof result = - fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.coordinator.commitPaidCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed) + : fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING); + verifyNoInteractions(hosting); + verify(fixture.eventProducer, never()) + .publishPaidCanonicalFirstJoinMembershipChange(any(), any(), any(), any(), any(), any()); assertThat(result).isEqualTo(fixture.expectedProof); assertThat(fixture.minimalAuditEnvelope.payload()).isNull(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 0994167f40..ce2a8df7d8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -31,6 +31,8 @@ import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -83,6 +85,94 @@ class AccountCanonicalPublicRealmScopeOwnerTest { private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final long PRIVATE_ACCOUNT = 41L; private static final String NAMESPACE = "prod"; + + @Test + void directProducerUsesExactGameSessionPeerAndCurrentOwnersWithoutBootstrapRegistry() { + Fixture f = new Fixture(300000L); + f.active.set(false); + var target = directTarget(f.target); + var caller = directCaller(f.target); + java.util.concurrent.atomic.AtomicReference result = + new java.util.concurrent.atomic.AtomicReference<>(); + directPeer(NAMESPACE, "game-session-service") + .run(() -> result.set(f.owner.issueDirectTextScope(caller, target).scope())); + + CanonicalJoinScopeV2 scope = result.get(); + assertThat(scope.accountId()).isEqualTo(ACCOUNT); + assertThat(scope.tenantId()).isEqualTo(TENANT); + assertThat(scope.gameInstanceId()).isEqualTo(f.target.canonicalGameInstanceId()); + assertThat(f.retained.get()).isEqualTo(scope); + assertThat(f.registryChecks.get()).isZero(); + assertThat(Instant.parse(scope.connectScopeExpiresAt())).isAfter(f.clock.instant()); + verifyNoInteractions(f.sessions); + verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); + } + + @ParameterizedTest + @ValueSource(strings = {"other-namespace", "wrong-service"}) + void directProducerRefusesWrongPeerBeforeReadingAccountOrSources(String mismatch) { + Fixture f = new Fixture(300000L); + var peer = + directPeer( + mismatch.equals("other-namespace") ? "other" : NAMESPACE, + mismatch.equals("wrong-service") ? "world-management-service" : "game-session-service"); + peer.run( + () -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); + verifyNoInteractions(f.scopes, f.sessions, f.targets, f.entitlements); + } + + @Test + void directProducerRechecksCurrentAccountAndTargetBeforePersistingScope() { + Fixture f = new Fixture(300000L); + f.onSecondTargetRead = + () -> f.account.setLifecycleState(AccountLifecycleState.DEACTIVATED_PENDING_DELETE); + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + verifyNoInteractions(f.scopes, f.sessions); + } + + private static io.grpc.Context directPeer(String namespace, String service) { + return io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service)); + } + + private static DirectTextCallerContext directCaller(Target target) { + return new DirectTextCallerContext( + ACCOUNT, + target.canonicalTenantId(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "direct-request"); + } + + private static DirectTextJoinTarget directTarget(Target target) { + return new DirectTextJoinTarget( + target.canonicalTenantId(), + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + } + private static final String HASH = "a".repeat(64); @AfterEach @@ -200,6 +290,70 @@ void exactTenantWorldSelectionNeverUsesABareGlobalWorldOrAnotherTenant() { verifyNoInteractions(f.entitlements, f.memberships, f.scopes); } + @Test + void globallyUniqueWorldUsesTheExactSourceTenantAndRetainedV2Scope() { + Fixture f = new Fixture(300000L); + + var result = f.owner.listRealmScopes(f.token, "world").getFirst(); + + assertThat(result.target()).isEqualTo(f.target); + assertThat(result.scope().tenantId()).isEqualTo(f.target.canonicalTenantId()); + assertThat(result.scope().tenantSlug()).isEqualTo(f.target.tenantSlug()); + assertThat(result.scope()).isEqualTo(f.retained.get()); + verify(f.entitlements).evaluate(TENANT); + } + + @Test + void globalWorldAmbiguityRefusesBeforeEntitlementOrAccountScopeSources() { + Fixture f = new Fixture(300000L); + Target other = target(UUID.randomUUID(), "another-tenant", 1L); + f.firstCollection = List.of(f.target, other); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "world")); + + verifyNoInteractions(f.entitlements, f.tenants, f.heads, f.memberships, f.scopes); + assertThat(f.transactions.started).isZero(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void globalWorldTenantReplacementOrNewAmbiguityOnRereadCannotPublishScope(boolean ambiguous) { + Fixture f = new Fixture(300000L); + Target other = target(UUID.randomUUID(), "another-tenant", 1L); + f.secondCollection = ambiguous ? List.of(f.target, other) : List.of(other); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "world")); + + verifyNoInteractions(f.scopes); + verify(f.entitlements).evaluate(TENANT); + } + + @Test + void qualifiedWorldSelectionUsesTheSamePipelineWithinTheCompleteCollection() { + Fixture f = new Fixture(300000L); + Target other = target(UUID.randomUUID(), "another-tenant", 1L); + f.firstCollection = List.of(f.target, other); + f.secondCollection = f.firstCollection; + + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); + + assertThat(result.scope().tenantId()).isEqualTo(TENANT); + assertThat(result.target()).isEqualTo(f.target); + } + + @Test + void globalWorldAbsenceIsRereadWithoutMintingAndMalformedCallerPrecedesSelection() { + Fixture f = new Fixture(300000L); + f.firstCollection = List.of(); + f.secondCollection = List.of(); + + assertCode("CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes("malformed", "world")); + verifyNoInteractions(f.targets, f.entitlements, f.scopes); + assertThat(f.owner.listRealmScopes(f.token, "world")).isEmpty(); + assertThat(f.targetReads.get()).isEqualTo(2); + verifyNoInteractions(f.entitlements, f.scopes, f.memberships); + } + @Test void changedIndependentTargetReadRefusesBeforeAnyScopeWrite() { Fixture f = new Fixture(300000L); @@ -429,6 +583,8 @@ private static final class Fixture { private final String token; private final AccountCanonicalPublicRealmScopeOwner owner; private Target secondTarget = target; + private List firstCollection; + private List secondCollection; private Runnable onSecondTargetRead = () -> {}; private boolean corruptReadback; private boolean corruptDigest; @@ -496,7 +652,10 @@ private Fixture(long bootstrapLifetime) { if (count == 2) onSecondTargetRead.run(); var request = new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); - List values = List.of(count == 1 ? target : secondTarget); + List values = + count == 1 + ? (firstCollection == null ? List.of(target) : firstCollection) + : (secondCollection == null ? List.of(secondTarget) : secondCollection); return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( request, CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( @@ -705,6 +864,10 @@ private static FreshTenantCreationEvidence source() { } private static Target target(long pointer) { + return target(TENANT, "tenant", pointer); + } + + private static Target target(UUID tenantId, String tenantSlug, long pointer) { UUID realm = UUID.randomUUID(); UUID playableNamespace = UUID.randomUUID(); UUID instance = UUID.randomUUID(); @@ -715,7 +878,7 @@ private static Target target(long pointer) { var request = new WorldCanonicalInitialAdmissionHold.Request( NAMESPACE, - TENANT, + tenantId, "world", realm, playableNamespace, @@ -731,8 +894,8 @@ private static Target target(long pointer) { var hold = new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, holdId, holdFence); return new Target( NAMESPACE, - "tenant", - TENANT, + tenantSlug, + tenantId, "world", "World", realm, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 48e957464f..14234211d1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; @@ -45,6 +46,10 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -54,6 +59,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCurrentRecord; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; @@ -93,8 +99,9 @@ void clearTransactionState() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); } - @Test - void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); DemoTenantEntitlementSnapshot currentEntitlement = @@ -145,9 +152,17 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { }); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + var currentPaidReceipt = paidReceipt(fixture.currentTenantEvent(), 5, true); + when(hosting.readCurrent(fence, observed)).thenReturn(currentPaidReceipt); Checkpoint checkpoint = - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed) + : fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING); MembershipEvent event = MembershipAuthorityEventV1Codec.verify( @@ -168,7 +183,13 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { new MembershipAuthorityEventV1Codec.TenantBillingCutoff( "2", "1", "account:auth-authority:v1:tenant/" + TENANT_UUID, "1"))); verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); - verify(fixture.entitlements).readCurrent(TENANT_UUID); + if (paid) { + verify(hosting).readCurrent(fence, observed); + verifyNoInteractions(fixture.entitlements); + } else { + verify(fixture.entitlements).readCurrent(TENANT_UUID); + verifyNoInteractions(hosting); + } var order = inOrder(fixture.accounts, fixture.joinOperations, fixture.memberships); order.verify(fixture.accounts).findByAccountUuid(ACCOUNT_UUID); @@ -180,8 +201,9 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { verify(fixture.pairs).commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class)); } - @Test - void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); Event event = fixture.existingEvent(); @@ -210,9 +232,19 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() .thenThrow(new IllegalStateException("current entitlement is no longer available")); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); Checkpoint replay = - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + hosting, + mock(ReadFence.class), + mock(StripeHostingSubscriptionObserver.ObservedSubscription.class)) + : fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING); + verifyNoInteractions(hosting); assertThat(replay).isEqualTo(checkpoint); verify(fixture.outbox, never()) @@ -667,6 +699,88 @@ void eventPublicationRequiresWritableAccountTransactionBeforeAnyLookup() { fixture.tenantAuthorityEvents); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"version", "denied", "billing", "unavailable"}) + void paidMismatchOrUnavailableSourceNeverPublishesOrFallsBack(String failure) { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + var receipt = + paidReceipt( + fixture.currentTenantEvent(), + "version".equals(failure) ? 6 : 5, + !"denied".equals(failure)); + if ("billing".equals(failure)) { + receipt = + new AccountHostingSubscriptionCurrentReceipt( + receipt.current(), + receipt.receiptRequestId(), + receipt.subscriptionStatus(), + true, + true, + true, + true, + 5, + 9, + receipt.billingEventId(), + receipt.billingEventDigest(), + receipt.tenantAuthorityEvent(), + "active", + receipt.currentPeriodStart(), + receipt.currentPeriodEnd(), + false, + null, + null, + receipt.evaluatedAt(), + receipt.validUntil()); + } + if ("unavailable".equals(failure)) + when(hosting.readCurrent(fence, observed)) + .thenThrow(new IllegalStateException("controlled paid source unavailable")); + else when(hosting.readCurrent(fence, observed)).thenReturn(receipt); + fixture.startWritableTransaction(); + assertThatThrownBy( + () -> + fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(fixture.entitlements); + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + private static AccountHostingSubscriptionCurrentReceipt paidReceipt( + TenantAuthorityEventV1Codec.Event event, long version, boolean allowJoin) { + var current = mock(AccountSubscriptionCurrentRecord.class); + when(current.tenantId()).thenReturn(TENANT_UUID); + Instant now = Instant.parse("2026-11-02T00:00:00Z"); + return new AccountHostingSubscriptionCurrentReceipt( + current, + UUID.randomUUID(), + Status.ACTIVE, + true, + allowJoin, + true, + true, + version, + event.tenantBillingSequence(), + event.tenantBillingEventId(), + event.tenantBillingEventDigest(), + event, + "active", + now.minusSeconds(100), + now.plusSeconds(1000), + false, + null, + null, + now, + now.plusSeconds(60)); + } + private void denyLaterTenantSource(TenantAuthorityEventV1Codec.Event event) { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java new file mode 100644 index 0000000000..9e3654d9da --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -0,0 +1,941 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanQuote; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCurrentRecord; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled source doubles prove composition and denial, not authenticated custody or SQL locks. + */ +class AccountPlayerAdmissionEntitlementOwnerTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String ISSUER = "firemud-account-service"; + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String PREFIX = "account:auth-authority:v1:"; + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final String HASH = "a".repeat(64); + + @AfterEach + void clearTransactionFlags() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTarget() + throws Exception { + Fixture f = new Fixture(false); + var value = f.owner.evaluate(f.request, "controlled-token"); + assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); + assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); + assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); + assertThat(value.membershipSource().accountId()).isEqualTo(ACCOUNT.toString()); + assertThat(value.membershipSource().tenantId()).isEqualTo(TENANT.toString()); + assertThat(value.membershipSource().membershipExists()).isFalse(); + assertThat(value.membershipSource().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isFalse(); + assertThat(value.membershipSource().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(value.membershipSource().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("1"); + assertThat(value.membershipSource().authorityTuple().membershipAuthorityGeneration()) + .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); + assertThat(value.fields()) + .containsEntry("verifiedConnectScopeId", f.scope.connectScopeId()) + .containsEntry("sourceKind", "NON_PAID_DEMO"); + var binding = (Map) value.fields().get("target"); + assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); + assertThat(binding.get("pointerVersion")).isEqualTo("3"); + assertThat(value.toString()).doesNotContain("controlled-token", f.scope.connectScopeId()); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + verifyNoInteractions(f.hosting, f.observer); + } + + @Test + void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { + Fixture f = new Fixture(true); + var value = f.owner.evaluate(f.request, "controlled-token"); + assertThat(value.membershipSource().membershipExists()).isTrue(); + assertThat(value.membershipSource().membershipVersion()) + .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); + assertThat(value.membershipSource().sourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.eventId()).isEqualTo("membership-event-1"); + assertThat(source.eventDigest()).startsWith("sha256:"); + }); + var order = inOrder(f.accounts, f.issuances, f.memberships, f.scopes, f.demos); + order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + order.verify(f.issuances).readCurrentCommittedCandidateByJti(f.identity.tokenJti()); + order.verify(f.memberships).readCurrent(ACCOUNT, TENANT); + order.verify(f.scopes).findCanonical(f.scope.connectScopeId()); + order + .verify(f.scopes) + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + order.verify(f.demos).readCurrent(TENANT); + } + + @ParameterizedTest + @EnumSource(Status.class) + void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTransaction( + Status status) throws Exception { + Fixture f = new Fixture(true); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.hosting.prepareCurrentRead(TENANT)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return fence; + }); + when(f.observer.observe(fence.binding())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return observed; + }); + when(f.hosting.readCurrent(fence, observed)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return f.receipt(status); + }); + var value = f.owner.evaluate(f.request, "controlled-token"); + assertThat(value.fields()) + .containsEntry("sourceKind", "PAID_HOSTING") + .containsEntry("subscriptionStatus", status.storageValue()) + .containsEntry("tenantBillingSequence", "1") + .containsEntry("tenantAuthorityGeneration", "2"); + boolean available = status != Status.SUSPENDED && status != Status.CANCELED; + assertThat(value.fields()) + .containsEntry("gameplayAvailable", available) + .containsEntry("allowPublicJoin", available && status != Status.GRACE) + .containsEntry("allowNewGameplayBindings", available && status != Status.GRACE) + .containsEntry("allowNewInstanceStarts", available && status != Status.GRACE); + assertThat(f.transactions.events) + .containsExactly("begin", "commit", "begin", "commit", "begin", "commit"); + var order = inOrder(f.observer, f.accounts, f.hosting); + order.verify(f.hosting).prepareCurrentRead(TENANT); + order.verify(f.observer).observe(fence.binding()); + order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + order.verify(f.hosting).readCurrent(fence, observed); + } + + @Test + void scopeDeadlineReachedDuringFinalCommitReturnsNoValue() throws Exception { + Fixture f = new Fixture(false); + f.transactions.afterSecondCommit = () -> f.time.set(NOW.plusSeconds(60)); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("expired"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @Test + void callerAccountMismatchFailsBeforeAnySourceRead() throws Exception { + Fixture f = new Fixture(false); + var original = f.request.target(); + var other = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + original.readRequestId(), + UUID.randomUUID(), + original.targetNamespace(), + original.tenantId(), + original.tenantSlug(), + original.worldSlug(), + original.realmId(), + original.realmSlug(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.gameInstanceId(), + original.catalogRevision(), + original.pointerVersion()); + assertThatThrownBy( + () -> + f.owner.evaluate( + new Request(other, f.scope.connectScopeId(), PEER), "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions( + f.accounts, + f.issuances, + f.memberships, + f.scopes, + f.sources, + f.demos, + f.hosting, + f.observer, + f.targets); + } + + @Test + void unavailableOrChangedAccountSourceHeadNeverChoosesAnotherFamily() throws Exception { + Fixture f = new Fixture(false); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenThrow(new IllegalStateException("controlled missing source")); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled missing source"); + verifyNoInteractions(f.demos, f.hosting, f.observer, f.targets); + + Fixture changed = new Fixture(false); + when(changed.sources.readCurrentSourceSelection(TENANT)) + .thenReturn( + new SourceSelection(SourceKind.NON_PAID_DEMO, changed.tenantEvent), + new SourceSelection(SourceKind.PAID_HOSTING, changed.tenantEvent)); + assertThatThrownBy(() -> changed.owner.evaluate(changed.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(changed.demos, changed.hosting, changed.observer); + } + + @Test + void currentCallerLossDoesNotBecomeTenantOrBillingOwnerAuthority() throws Exception { + Fixture f = new Fixture(false); + when(f.issuances.readCurrentCommittedCandidateByJti(f.identity.tokenJti())) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.scopes, f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "rollback"); + } + + @Test + void absentCanonicalScopeRefusesPrivatePlaytestAndNumericScopeAliases() throws Exception { + Fixture f = new Fixture(false); + when(f.scopes.findCanonical(f.scope.connectScopeId())).thenReturn(Optional.empty()); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + @Test + void anotherAccountsScopeFailsBeforeEntitlementCapture() throws Exception { + Fixture f = new Fixture(false); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn( + Optional.of(f.scopeEvidence(UUID.randomUUID(), f.scope.connectScopeExpiresAt()))); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.demos); + } + + @Test + void expiredScopeDoesNotReturnCapturedAuthority() throws Exception { + Fixture f = new Fixture(false); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn(Optional.of(f.scopeEvidence(ACCOUNT, NOW.toString()))); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transactions.events).containsExactly("begin", "commit"); + } + + @Test + void changedTenantCheckpointCannotBeCombinedWithAnOlderEntitlement() throws Exception { + Fixture f = new Fixture(false); + var original = f.demo; + var changed = + new DemoTenantEntitlementSnapshot( + TENANT, + f.source, + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + true, + true, + true, + true, + original.quotas(), + 1, + 2, + 2, + original.outboxStreamKey(), + 1, + original.eventId(), + original.eventDigest(), + original.snapshotIdentity(), + original.tenantAuthorityOutboxStreamKey(), + 2, + original.tenantAuthorityEventId(), + original.tenantAuthorityEventDigest()); + when(f.demos.readCurrent(TENANT)).thenReturn(changed); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + + @Test + void commitFailureReturnsNoEvidence() throws Exception { + Fixture f = new Fixture(false); + f.transactions.failCommit = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled commit failure"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @Test + void wrongWorkloadAndAmbientTransactionFailBeforeCallerOrSourceReads() throws Exception { + Fixture f = new Fixture(false); + Request wrongPeer = + new Request( + f.request.target(), + f.scope.connectScopeId(), + "spiffe://firemud/ns/other/sa/game-session-service"); + assertThatThrownBy(() -> f.owner.evaluate(wrongPeer, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions( + f.callers, + f.accounts, + f.issuances, + f.memberships, + f.scopes, + f.demos, + f.hosting, + f.observer); + } + + @Test + void unavailableProtectedTargetReturnsNoValueOrAlternateEntitlementSource() throws Exception { + Fixture f = new Fixture(false); + doThrow(new IllegalStateException("controlled target unavailable")) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(any()); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled target unavailable"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit"); + } + + @Test + void changedOwnerPointerFailsExactRetainedTargetComparison() throws Exception { + Fixture f = new Fixture(false); + var selector = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + f.request.requestId(), + ACCOUNT, + "prod", + TENANT, + f.scope.tenantSlug(), + f.scope.worldSlug(), + f.scope.realmId(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + "SHARED", + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion()); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(selector); + when(resolved.currentTarget().pointerVersion()).thenReturn(f.scope.pointerVersion() + 1); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("retained"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + @Test + void scopeChangedDuringProtectedTargetReadCannotBindFinalAccountEvidence() throws Exception { + Fixture f = new Fixture(false); + var original = f.scopeEvidence(ACCOUNT, f.scope.connectScopeExpiresAt()); + var changed = f.scopeEvidence(ACCOUNT, NOW.plusSeconds(50).toString()); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn(Optional.of(original), Optional.of(changed)); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.demos); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + + @Test + void strictProtectedReadFailureNeverProducesCanonicalPlayerEvidence() throws Exception { + Fixture f = new Fixture(false); + var selector = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + f.request.requestId(), + ACCOUNT, + "prod", + TENANT, + f.scope.tenantSlug(), + f.scope.worldSlug(), + f.scope.realmId(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + "SHARED", + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion()); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(selector); + when(f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())) + .thenThrow(new IllegalStateException("controlled World source stale")); + // Keep that exact resolver result so the strict-read denial cannot be replaced by new stubbing. + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled World source stale"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ + private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { + when(targets.resolvePublishedRealmAdmissionTarget(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + .class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer( + readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return read; + }); + return resolved; + }); + } + + private static final class Fixture { + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountGameplayAdmissionCallerVerifier callers = + mock(AccountGameplayAdmissionCallerVerifier.class); + private final AccountGameplayDelegationIssuanceRepository issuances = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final AccountHostingSubscriptionLifecycleRepository hosting = + mock(AccountHostingSubscriptionLifecycleRepository.class); + private final StripeHostingSubscriptionObserver observer = + mock(StripeHostingSubscriptionObserver.class); + private final AccountDemoTenantEntitlementRepository demos = + mock(AccountDemoTenantEntitlementRepository.class); + private final AccountTenantAuthorityEventRepository sources = + mock(AccountTenantAuthorityEventRepository.class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final RecordingTransactions transactions = new RecordingTransactions(); + private final java.util.concurrent.atomic.AtomicReference time = + new java.util.concurrent.atomic.AtomicReference<>(NOW); + private final FreshTenantCreationEvidence source = source(); + private final TenantAuthorityEventV1Codec.Event tenantEvent = tenantEvent(source); + private final CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "private-bearer-" + UUID.randomUUID(), + ACCOUNT, + TENANT, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + NOW.minusSeconds(20).toString(), + NOW.plusSeconds(60).toString()); + private final AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + ACCOUNT, + PEER, + UUID.randomUUID(), + mock(AccountGameplayCredentialRequestBinding.class), + HASH, + UUID.randomUUID(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond()); + private final DemoTenantEntitlementSnapshot demo = + new DemoTenantEntitlementSnapshot( + TENANT, + source, + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096), + 1, + 2, + 2, + tenantEvent.tenantBillingStreamKey(), + 1, + tenantEvent.tenantBillingEventId(), + tenantEvent.tenantBillingEventDigest(), + tenantEvent.tenantBillingEventDigest(), + tenantEvent.outboxStreamKey(), + 1, + tenantEvent.eventId(), + tenantEvent.eventDigest()); + private final Request request = + new Request( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + ACCOUNT, + "prod", + TENANT, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()), + scope.connectScopeId(), + PEER); + private final AccountPlayerAdmissionEntitlementOwner owner; + + private Fixture(boolean exists) throws Exception { + controlledTarget(targets); + var dsl = mock(DSLContext.class); + var connection = mock(Connection.class); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + var candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()) + .thenReturn(new AccountAuthoritySnapshot(ACCOUNT, 1, 1, 1, 1, 1, 1, Optional.empty())); + when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); + when(candidate.signerCorrespondence()) + .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); + when(candidate.tokenSha256()).thenReturn(HASH); + when(candidate.signerKid()).thenReturn("controlled-kid"); + when(candidate.signerGeneration()).thenReturn("1"); + when(candidate.canonicalRegistryRecordSha256()).thenReturn(HASH); + when(candidate.commitProofSha256()).thenReturn(HASH); + when(candidate.envelopeKeyId()).thenReturn("controlled-envelope-key"); + when(candidate.envelopeSha256()).thenReturn(HASH); + var caller = mock(VerifiedCaller.class); + when(caller.identity()).thenReturn(identity); + when(caller.currentCandidate()).thenReturn(candidate); + when(callers.verifyPresentedCompactToken("controlled-token")) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return caller; + }); + Account account = new Account(); + account.setId(10L); + account.setAccountUuid(ACCOUNT); + when(accounts.findByAccountUuidForUpdate(ACCOUNT)).thenReturn(Optional.of(account)); + when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) + .thenReturn(Optional.of(candidate)); + when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(snapshot(exists)); + when(scopes.findCanonical(scope.connectScopeId())).thenReturn(Optional.of(scope)); + when(scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(scope.connectScopeId()))) + .thenReturn(Optional.of(scopeEvidence(ACCOUNT, scope.connectScopeExpiresAt()))); + when(demos.readCurrent(TENANT)).thenReturn(demo); + when(sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.NON_PAID_DEMO, tenantEvent)); + Clock clock = mock(Clock.class); + when(clock.instant()).thenAnswer(invocation -> time.get()); + owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + callers, + issuances, + memberships, + scopes, + hosting, + observer, + demos, + sources, + targets, + transactions, + clock, + "prod"); + } + + private CanonicalConnectScopeEvidence scopeEvidence(UUID account, String expiry) { + return new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + 10, + "PUBLIC_PRODUCTION", + account, + TENANT, + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + expiry, + 2, + AccountJoinDigest.scopeV2(scope), + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest())); + } + + private AccountHostingSubscriptionCurrentReceipt receipt(Status status) { + var current = mock(AccountSubscriptionCurrentRecord.class); + when(current.tenantId()).thenReturn(TENANT); + when(current.subscriptionId()).thenReturn(UUID.randomUUID()); + when(current.rowVersion()).thenReturn(2L); + when(current.planQuote()) + .thenReturn(new AccountHostingPlanQuote("standard", "price_Test", 1, 3, 2, 4096)); + return new AccountHostingSubscriptionCurrentReceipt( + current, + UUID.randomUUID(), + status, + status != Status.SUSPENDED && status != Status.CANCELED, + status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, + status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, + status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, + 1, + 1, + tenantEvent.tenantBillingEventId(), + tenantEvent.tenantBillingEventDigest(), + tenantEvent, + "active", + NOW.minusSeconds(100), + NOW.plusSeconds(1000), + false, + null, + null, + NOW, + NOW.plusSeconds(60)); + } + + private Snapshot snapshot(boolean exists) { + var cutoff = new TenantBillingCutoff("2", "1", tenantEvent.outboxStreamKey(), "1"); + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of(Map.of(TENANT.toString(), cutoff))); + List events = new ArrayList<>(); + if (exists) { + Map event = new LinkedHashMap<>(); + event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + event.put("eventId", "membership-event-1"); + event.put("requestId", "membership-request-1"); + event.put("outboxStreamKey", memberStream()); + event.put("outboxSequence", "1"); + event.put("sourceScope", "membership/" + ACCOUNT + "/" + TENANT); + event.put("accountId", ACCOUNT.toString()); + event.put("tenantId", TENANT.toString()); + event.put("membershipExists", true); + event.put("membershipLifecycleState", "ACTIVE"); + event.put("membershipVersion", Map.of(TENANT.toString(), "1")); + event.put("membershipAuthorityGeneration", "1"); + event.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(TENANT.toString(), "1"), + "privateRealmGrantVersions", + List.of(), + "tenantBillingCutoff", + Map.of( + TENANT.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + tenantEvent.outboxStreamKey(), + "outboxSequence", + "1")))); + event.put("issuanceFence", "1"); + event.put("roles", List.of("player")); + event.put("gameplayAdmissionAllowed", true); + event.put("callerBoundAuthorityInvalidated", false); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + events.add( + new SourceEvidence( + memberStream(), + "1", + sealed.eventId(), + sealed.eventDigest(), + sealed.canonicalJson())); + } + events.add( + new SourceEvidence( + tenantEvent.outboxStreamKey(), + "1", + tenantEvent.eventId().toString(), + tenantEvent.eventDigest(), + new String(tenantEvent.payload(), java.nio.charset.StandardCharsets.UTF_8))); + return new Snapshot( + ISSUER, + ACCOUNT.toString(), + TENANT.toString(), + exists, + exists ? "ACTIVE" : "MISSING", + exists, + Map.of(TENANT.toString(), "1"), + "1", + exists ? List.of("player") : List.of(), + tuple, + "1", + List.of( + new Checkpoint(PREFIX + "account/" + ACCOUNT, "0"), + new Checkpoint(PREFIX + "issuer/" + ISSUER, "0"), + new Checkpoint(memberStream(), exists ? "1" : "0"), + new Checkpoint(tenantEvent.outboxStreamKey(), "1")), + events); + } + } + + private static String memberStream() { + return PREFIX + "membership/" + ACCOUNT + "/" + TENANT; + } + + private static FreshTenantCreationEvidence source() { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, "world", "World", null); + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", requestId, operationId, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + } + + private static TenantAuthorityEventV1Codec.Event tenantEvent(FreshTenantCreationEvidence source) { + UUID requestId = UUID.randomUUID(); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + "sha256:" + HASH, + TENANT, + source.creationRequestId(), + source.requestDigest()); + var receipt = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + requestId, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + HASH); + return TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, receipt); + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private final List events = new ArrayList<>(); + private boolean failCommit; + private Runnable afterSecondCommit = () -> {}; + + @Override + public TransactionStatus getTransaction( + @org.jspecify.annotations.Nullable TransactionDefinition definition) { + if (definition != null) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.isReadOnly()).isFalse(); + } + events.add("begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("commit"); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (events.size() == 4) afterSecondCommit.run(); + if (failCommit && events.size() == 4) + throw new IllegalStateException("controlled commit failure"); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} 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 8b9ae9da40..6610dfbc34 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,6 +86,10 @@ class AccountGrpcServiceTest { private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; + private static final UUID DIRECT_TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID DIRECT_INSTANCE = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String DIRECT_SESSION = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/game-session-service", @@ -105,12 +109,12 @@ class AccountGrpcServiceTest { private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setTenantId("20") + .setTenantId(DIRECT_TENANT.toString()) .setRealmId(REALM_ID) .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setPlayableStateScope("realm:30") - .setGameInstanceId("40") - .setSessionId("session-1") + .setPlayableStateScope("SHARED") + .setGameInstanceId(DIRECT_INSTANCE.toString()) + .setSessionId(DIRECT_SESSION) .setRequestId("request-1") .build(); } @@ -118,13 +122,13 @@ private static PlayerExecutionContext validPlayerContext() { private static IssueDirectTextConnectScopeRequest validScopeRequest() { return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(validPlayerContext()) - .setTenantId("20") + .setTenantId(DIRECT_TENANT.toString()) .setRealmId(REALM_ID) .setWorldSlug("world") .setRealmSlug("public") .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setPlayableStateScope("realm:30") - .setGameInstanceId("40") + .setPlayableStateScope("SHARED") + .setGameInstanceId(DIRECT_INSTANCE.toString()) .setCatalogRevision(5) .setPointerVersion(8) .build(); @@ -228,29 +232,29 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); assertTrue(observer.completed()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).resolveAccountStorageId(Mockito.any()); assertEquals("scope-1", observer.response().getConnectScopeId()); assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); assertEquals("2026-09-24T11:59:30Z", observer.response().getEvaluatedAt()); Mockito.verify(accountService) .issueDirectTextConnectScope( new DirectTextCallerContext( - 10L, - 20L, + UUID.fromString(ACCOUNT_UUID), + DIRECT_TENANT, UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "realm:30", - 40L, - "session-1", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + DIRECT_INSTANCE, + DIRECT_SESSION, "request-1"), new DirectTextJoinTarget( - 20L, + DIRECT_TENANT, UUID.fromString(REALM_ID), "world", "public", - PLAYABLE_STATE_NAMESPACE_ID, - "realm:30", - 40L, + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + DIRECT_INSTANCE, 5L, 8L)); } @@ -332,7 +336,15 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { Mockito.any(JoinPublicProductionRequest.class))) .thenReturn( new JoinPublicProductionResult( - false, "ENTITLEMENT_UNAVAILABLE", ACCOUNT_UUID, 20L, 0L, 0L, 0L, true)); + false, + "ENTITLEMENT_UNAVAILABLE", + ACCOUNT_UUID, + DIRECT_TENANT, + 0L, + 0L, + 0L, + false, + true)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -345,24 +357,54 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { assertFalse(observer.response().getSuccess()); assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); - assertEquals("20", observer.response().getTenantId()); + assertEquals(DIRECT_TENANT.toString(), observer.response().getTenantId()); assertEquals("0", observer.response().getMembershipId()); assertTrue(observer.response().getReplayed()); assertFalse(observer.response().hasError()); Mockito.verify(accountService) .joinPublicProductionFromGameSession( new DirectTextCallerContext( - 10L, - 20L, + UUID.fromString(ACCOUNT_UUID), + DIRECT_TENANT, UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "realm:30", - 40L, - "session-1", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + DIRECT_INSTANCE, + DIRECT_SESSION, "request-1"), new JoinPublicProductionRequest("scope-1", "request-1")); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void successfulJoinProjectsTheActualMembershipAdmissionFlag(boolean admitting) { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.joinPublicProductionFromGameSession(Mockito.any(), Mockito.any())) + .thenReturn( + new JoinPublicProductionResult( + true, + admitting ? "JOINED" : "ALREADY_ACTIVE", + ACCOUNT_UUID, + DIRECT_TENANT, + 7L, + 3L, + 2L, + admitting, + false)); + var service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + var observer = new RecordingObserver(); + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + assertTrue(observer.response().getSuccess()); + assertEquals(admitting, observer.response().getGameplayAdmissionAllowed()); + assertEquals(DIRECT_TENANT.toString(), observer.response().getTenantId()); + assertEquals(3L, observer.response().getMembershipVersion()); + assertEquals(2L, observer.response().getMembershipAuthorityGeneration()); + assertFalse(observer.response().hasError()); + } + @Test void issueDirectTextConnectScopeMapsUnexpectedFailureToRetryableUnavailable() { PingService pingService = Mockito.mock(PingService.class); @@ -646,10 +688,13 @@ void joinRejectsUuidResultThatDoesNotMatchValidatedCaller(boolean changedAccount false, "ENTITLEMENT_UNAVAILABLE", changedAccount ? OTHER_ACCOUNT_UUID : ACCOUNT_UUID, - changedAccount ? 20L : 21L, + changedAccount + ? DIRECT_TENANT + : UUID.fromString("33333333-3333-4333-8333-333333333333"), 0L, 0L, 0L, + false, true)); AccountGrpcService service = new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java new file mode 100644 index 0000000000..ce61e144dd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Direct method calls cannot install the receiver's TLS-derived private peer assertion. */ +class AccountPlayerAdmissionEntitlementGrpcServiceTest { + @Test + @SuppressWarnings("unchecked") + void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() { + var owner = mock(AccountPlayerAdmissionEntitlementOwner.class); + var service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); + for (var request : + new ReadPlayerAdmissionEntitlementRequest[] { + null, + ReadPlayerAdmissionEntitlementRequest.getDefaultInstance(), + ReadPlayerAdmissionEntitlementRequest.newBuilder() + .addInitialLoginJwt("private-token".repeat(4000)) + .build() + }) { + StreamObserver observer = mock(StreamObserver.class); + + service.readPlayerAdmissionEntitlement(request, observer); + + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(failure.getValue().getMessage()).doesNotContain("private-token"); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + verifyNoInteractions(owner); + } +} 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 52ef20b55e..40bf244b69 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; @@ -13,6 +14,8 @@ import ch.qos.logback.core.read.ListAppender; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.time.Clock; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -21,13 +24,21 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; +import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; @@ -48,6 +59,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; @@ -61,16 +73,23 @@ import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner.RealmScope; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; +import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -81,12 +100,17 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; @Mock private AccountRepository accountRepository; @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @Mock private AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; @@ -100,6 +124,7 @@ class AccountServiceImplTest { accountPasswordResetDraftSourceChangeRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; + @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @@ -111,6 +136,8 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); + @Mock private GameSessionClient gameSessionClient; + @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; @Mock private PaymentTransactionRepository paymentTransactionRepository; @Mock private RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; @@ -181,107 +208,234 @@ private enum OrdinaryIssuance { PLAYER_BOOTSTRAP } - private enum PublicGameplayOperation { - WORLDS, - REALMS, - CHARACTERS, - BROWSER_JOIN, - DIRECT_SCOPE, - DIRECT_JOIN, - CONNECT_TOKEN + @Test + void bootstrapRealmsDelegatesWorldAndCredentialAndProjectsRetainedUuidScopeWithoutReminting() { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + UUID tenant = UUID.fromString("07aee9f3-a635-4b7f-aa66-86489320d7c3"); + UUID instance = UUID.fromString("3ddc3564-435b-479d-b14d-c91995e673cc"); + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "already-retained-v2-signed-scope", + UUID.fromString("e9e3aa54-9712-4e01-8767-f23f3c662e64"), + tenant, + UUID.fromString(REALM_ID), + "source-tenant", + "demo", + "production", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + instance, + 23L, + 17L, + "2026-11-03T00:00:00Z", + "2026-11-03T00:02:00Z"); + Target target = org.mockito.Mockito.mock(Target.class); + when(target.realmDisplayName()).thenReturn("Canonical realm"); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + RealmScope retained = org.mockito.Mockito.mock(RealmScope.class); + when(retained.target()).thenReturn(target); + when(retained.scope()).thenReturn(scope); + when(owner.listRealmScopes("canonical-bootstrap", "demo")).thenReturn(List.of(retained)); + org.mockito.Mockito.clearInvocations( + accountRepository, + sessionService, + gameSessionClient, + jwtUtil, + accountConnectScopeRepository, + retainedSubscriptionEvidenceRepository); + + var result = service.listBootstrapRealms("canonical-bootstrap", "demo").getFirst(); + + assertEquals(scope.worldSlug(), result.worldSlug()); + assertEquals(scope.realmSlug(), result.realmSlug()); + assertEquals(scope.realmId(), result.realmId()); + assertEquals(tenant, result.tenantId()); + assertEquals(instance, result.gameInstanceId()); + assertEquals(scope.playableStateNamespaceId(), result.playableStateNamespaceId()); + assertEquals(scope.pointerVersion(), result.pointerVersion()); + assertEquals(scope.catalogRevision(), result.catalogRevision()); + assertEquals("Canonical realm", result.displayName()); + assertEquals("PLAYABLE_STATE_SCOPE_SHARED", result.playableStateScope()); + assertEquals("SHARED", result.stateScope()); + assertEquals("PRESEEDED_ONLY", result.characterCreationPolicy()); + assertEquals(scope.evaluatedAt(), result.evaluatedAt()); + assertEquals(scope.connectScopeExpiresAt(), result.connectScopeExpiresAt()); + assertEquals(scope.connectScopeId(), result.connectScopeId()); + assertFalse(result.toString().contains(scope.connectScopeId())); + org.mockito.Mockito.verify(owner).listRealmScopes("canonical-bootstrap", "demo"); + verifyNoInteractions( + accountRepository, + sessionService, + gameSessionClient, + jwtUtil, + accountConnectScopeRepository, + retainedSubscriptionEvidenceRepository); + } + + @Test + void bootstrapRealmsWithoutCanonicalCompositionRefusesBeforeLegacySources() { + org.mockito.Mockito.clearInvocations(accountRepository, sessionService, gameSessionClient); + + AuthenticationException failure = + assertThrows( + AuthenticationException.class, () -> service.listBootstrapRealms("bootstrap", "demo")); + + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions(accountRepository, sessionService, gameSessionClient); } - /** The complete canonical positive fixtures remain in the public-facade successor. */ @ParameterizedTest - @EnumSource(PublicGameplayOperation.class) - void publicGameplayRemainsUnavailableBeforeReadingAnyCallerOrAuthority( - PublicGameplayOperation operation) { - AuthenticationException unavailable = + @ValueSource( + strings = { + "CONNECT_CONTEXT_INVALID", + "AUTH_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "ADMISSION_POINTER_UNAVAILABLE" + }) + void bootstrapRealmsPreservesCanonicalSourceRefusalWithoutFallback(String code) { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + AuthenticationException failure = new AuthenticationException(code, "Canonical source refusal"); + when(owner.listRealmScopes("bootstrap", "demo")).thenThrow(failure); + org.mockito.Mockito.clearInvocations(accountRepository, sessionService, gameSessionClient); + + assertSame( + failure, assertThrows( - AuthenticationException.class, - () -> invokePublicGameplayOperation(operation, null, null)); + AuthenticationException.class, () -> service.listBootstrapRealms("bootstrap", "demo"))); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - verifyPublicGameplayHasNoIo(); + verifyNoInteractions(accountRepository, sessionService, gameSessionClient); } @ParameterizedTest - @EnumSource( - value = PublicGameplayOperation.class, - names = "DIRECT_SCOPE", - mode = EnumSource.Mode.EXCLUDE) - void retainedNumericSignedCarriersCannotReenablePublicGameplay( - PublicGameplayOperation operation) { - String bootstrap = - jwtUtil.generateToken("11", 300000L, Map.of("aud", "player-bootstrap", "accountId", "11")); - String scope = - jwtUtil.generateToken( - "11", - 120000L, - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - "11", - "tenantId", - "7", - "gameInstanceId", - "44")); - org.mockito.Mockito.clearInvocations(jwtUtil); + @ValueSource(booleans = {false, true}) + void bootstrapRealmsRefusesAmbientSqlBeforeCanonicalSource(boolean synchronizationOnly) { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + if (synchronizationOnly) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThrows( + IllegalStateException.class, () -> service.listBootstrapRealms("bootstrap", "demo")); + verifyNoInteractions(owner); + } finally { + TransactionSynchronizationManager.clear(); + } + } - AuthenticationException unavailable = + @Test + void bootstrapRealmsKeepsPlayerContextForTheComposedOwnersWorkloadGuard() { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + SessionContext.setContext("e9e3aa54-9712-4e01-8767-f23f3c662e64", List.of(), Map.of()); + when(owner.listRealmScopes("bootstrap", "demo")) + .thenAnswer( + invocation -> { + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + throw new IllegalStateException("Canonical source requires workload-only context"); + }); + try { + assertThrows( + IllegalStateException.class, () -> service.listBootstrapRealms("bootstrap", "demo")); + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + } finally { + SessionContext.clear(); + } + } + + @Test + void bootstrapWorldsDelegatesExactCredentialAndCompleteResultToCanonicalOwner() { + AccountPublicBootstrapWorldsOwner owner = + org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); + service.setPublicBootstrapWorldsOwner(owner); + List worlds = + List.of(new BootstrapWorldDto("alpha", "Alpha"), new BootstrapWorldDto("zulu", "Zulu")); + when(owner.listWorlds("canonical-bootstrap")).thenReturn(worlds); + org.mockito.Mockito.clearInvocations(accountRepository, sessionService, gameSessionClient); + + assertSame(worlds, service.listBootstrapWorlds("canonical-bootstrap")); + + org.mockito.Mockito.verify(owner).listWorlds("canonical-bootstrap"); + verifyNoInteractions(accountRepository, sessionService, gameSessionClient); + } + + @Test + void bootstrapWorldsWithoutCanonicalCompositionRefusesBeforeLegacyDiscovery() { + org.mockito.Mockito.clearInvocations(accountRepository, sessionService, gameSessionClient); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds("bootstrap")); + + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions(accountRepository, sessionService, gameSessionClient); + } + + @ParameterizedTest + @ValueSource( + strings = {"AUTH_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"}) + void bootstrapWorldsPreservesCanonicalSourceFailureWithoutLegacyFallback(String code) { + AccountPublicBootstrapWorldsOwner owner = + org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); + service.setPublicBootstrapWorldsOwner(owner); + AuthenticationException unavailable = new AuthenticationException(code, "Source unavailable"); + when(owner.listWorlds("bootstrap")).thenThrow(unavailable); + org.mockito.Mockito.clearInvocations(accountRepository, sessionService, gameSessionClient); + + assertSame( + unavailable, assertThrows( - AuthenticationException.class, - () -> invokePublicGameplayOperation(operation, bootstrap, scope)); + AuthenticationException.class, () -> service.listBootstrapWorlds("bootstrap"))); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - verifyPublicGameplayHasNoIo(); - } - - private void invokePublicGameplayOperation( - PublicGameplayOperation operation, String bootstrap, String scope) { - JoinPublicProductionRequest join = - scope == null ? null : new JoinPublicProductionRequest(scope, UUID.randomUUID().toString()); - switch (operation) { - case WORLDS -> service.listBootstrapWorlds(bootstrap); - case REALMS -> service.listBootstrapRealms(bootstrap, "demo"); - case CHARACTERS -> service.listBootstrapCharacters(bootstrap, "demo", "production", scope); - case BROWSER_JOIN -> service.joinPublicProduction(bootstrap, join); - case DIRECT_SCOPE -> service.issueDirectTextConnectScope(null, null); - case DIRECT_JOIN -> service.joinPublicProductionFromGameSession(null, join); - case CONNECT_TOKEN -> - service.issueConnectToken( - bootstrap, - scope == null ? null : new ConnectTokenRequest(scope, UUID.randomUUID().toString())); + verifyNoInteractions(accountRepository, sessionService, gameSessionClient); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bootstrapWorldsRefusesAmbientTransactionOrSynchronizationBeforeCanonicalRead( + boolean synchronizationOnly) { + AccountPublicBootstrapWorldsOwner owner = + org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); + service.setPublicBootstrapWorldsOwner(owner); + if (synchronizationOnly) { + TransactionSynchronizationManager.initSynchronization(); + } else { + TransactionSynchronizationManager.setActualTransactionActive(true); + } + try { + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("bootstrap")); + + assertTrue(failure.getMessage().contains("ambient SQL")); + verifyNoInteractions(owner); + } finally { + TransactionSynchronizationManager.clear(); } } - private void verifyPublicGameplayHasNoIo() { - verifyNoInteractions( - accountRepository, - accountAuthorityGenerationRepository, - accountAuthoritySourceEvidenceRepository, - accountAuthorityOutboxRepository, - accountPasswordResetOperationRepository, - accountLogoutAllOperationRepository, - accountSecurityStateOperationRepository, - accountPasswordResetDraftSourceChangeRepository, - accountAuditOutboxRepository, - accountJoinOperationRepository, - accountEmailLoginChallengeRepository, - accountRealmAccessGrantRepository, - accountTenantMembershipRepository, - retainedSubscriptionEvidenceRepository, - paymentTransactionRepository, - profileRepository, - externalAccountRepository, - passwordResetTokenRepository, - emailVerificationTokenRepository, - notificationService, - emailService, - sessionService, - transactionManager, - jwtUtil); + @Test + void bootstrapWorldsRetainsPlayerContextAndCanonicalWorkloadGuard() { + var callerVerifier = org.mockito.Mockito.mock(AccountPlayerBootstrapCallerVerifier.class); + var targets = org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + var entitlements = org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); + service.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner( + callerVerifier, targets, entitlements, Clock.systemUTC())); + SessionContext.setContext("account", List.of(), Map.of()); + try { + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("bootstrap")); + + assertTrue(failure.getMessage().contains("workload-only")); + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + verifyNoInteractions(callerVerifier, targets, entitlements); + } finally { + SessionContext.clear(); + } } private enum IdentityFailure { @@ -680,28 +834,1312 @@ void createAccountRejectsPublicIdentityWithoutExactPersistedSourceRow() { } @Test - void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { - CreateAccountRequest request = - new CreateAccountRequest("demo", " DEMO@EXAMPLE.COM ", "password"); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) - .thenThrow(new org.jooq.exception.IntegrityConstraintViolationException("duplicate")); - - AccountAlreadyExistsException exception = - assertThrows(AccountAlreadyExistsException.class, () -> service.createAccount(request)); + void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { + CreateAccountRequest request = + new CreateAccountRequest("demo", " DEMO@EXAMPLE.COM ", "password"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenThrow(new org.jooq.exception.IntegrityConstraintViolationException("duplicate")); + + AccountAlreadyExistsException exception = + assertThrows(AccountAlreadyExistsException.class, () -> service.createAccount(request)); + + assertEquals("Account already exists", exception.getMessage()); + } + + @Test + void createAccountMapsSpringDataIntegrityConflict() { + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenThrow(new org.springframework.dao.DataIntegrityViolationException("duplicate")); + + AccountAlreadyExistsException exception = + assertThrows(AccountAlreadyExistsException.class, () -> service.createAccount(request)); + + assertEquals("Account already exists", exception.getMessage()); + } + + /** + * These fixtures prove facade ordering/projection; physical owner atomicity is integration proof. + */ + @ParameterizedTest + @CsvSource({"JOINED,2,1", "ALREADY_ACTIVE,7,3", "JOINED,8,3"}) + void canonicalJoinProjectsFirstActiveAndRestoredOwnerSnapshots( + String outcome, long version, long generation) { + var f = canonicalJoinFixture(); + f.terminal(outcome, version, generation); + var result = f.browserJoin(); + assertTrue(result.success()); + assertEquals(outcome, result.outcomeCode()); + assertEquals(f.scope.accountId().toString(), result.accountId()); + assertEquals(f.scope.tenantId(), result.tenantId()); + assertEquals(701L, result.membershipId()); + assertEquals(version, result.membershipVersion()); + assertEquals(generation, result.membershipAuthorityGeneration()); + assertFalse(result.replayed()); + assertTrue(result.gameplayAdmissionAllowed()); + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.times(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + verifyNoInteractions(f.hosting, f.observer, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + } + + @Test + void canonicalCommittedRetryRevalidatesCurrentPolicyBeforeReturningRetainedTerminalProof() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("COMMITTED"); + f.terminal("JOINED", 2L, 1L); + var result = f.browserJoin(); + assertTrue(result.success()); + assertTrue(result.replayed()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, f.binding, true, 1L); + org.mockito.Mockito.verify(f.sources, org.mockito.Mockito.times(2)) + .readCurrentSourceSelection(f.scope.tenantId()); + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + verifyNoInteractions(f.hosting, f.observer); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } + + @Test + void canonicalCommittedRetryCannotUseUnavailableCurrentEntitlementOrRewriteTerminalBytes() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("COMMITTED"); + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow(new DataAccessResourceFailureException("controlled current source outage")); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinWithoutConsumerCompositionRefusesBeforeLegacyIntentOrAuthorityWork() { + assertEquals( + "AUTH_UNAVAILABLE", + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + "bootstrap", new JoinPublicProductionRequest("scope", "request"))) + .getCode()); + verifyNoInteractions( + accountRepository, + accountJoinOperationRepository, + accountConnectScopeRepository, + accountTenantMembershipRepository, + gameSessionClient, + retainedSubscriptionEvidenceRepository); + } + + @Test + void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMutation() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("FAILED"); + when(f.pending.outcome()).thenReturn("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + var result = f.browserJoin(); + assertFalse(result.success()); + assertTrue(result.replayed()); + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", result.outcomeCode()); + verifyNoInteractions(f.sources, f.demos, f.hosting, f.observer, f.terminal); + } + + @ParameterizedTest + @CsvSource({ + "true,false,PUBLIC_PRODUCTION_ADMISSION_DENIED", + "false,false,TENANT_BILLING_BLOCKED" + }) + void canonicalJoinRetainsAuthoritativePolicyDenialsWithoutCallingTransitionOwner( + boolean gameplay, boolean open, String code) { + var f = canonicalJoinFixture(); + when(f.demo.gameplayAvailable()).thenReturn(gameplay); + when(f.demo.allowPublicJoin()).thenReturn(open); + var result = f.browserJoin(); + assertFalse(result.success()); + assertEquals(code, result.outcomeCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, code); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalActiveMemberCanReturnCurrentSnapshotWithClosedEnrollment() { + var f = canonicalJoinFixture(); + when(f.demo.allowPublicJoin()).thenReturn(false); + AccountTenantMembership current = f.currentMembership; + current.setLifecycleState("ACTIVE"); + current.setGameplayAdmissionAllowed(true); + current.setMembershipVersion(7L); + current.setMembershipAuthorityGeneration(3L); + org.mockito.Mockito.doReturn(Optional.of(current)) + .when(accountTenantMembershipRepository) + .findFreshMembershipForUpdate(f.scope.accountId(), f.scope.tenantId()); + f.terminal("ALREADY_ACTIVE", 7L, 3L); + var result = f.browserJoin(); + assertTrue(result.success()); + assertEquals("ALREADY_ACTIVE", result.outcomeCode()); + assertEquals(7L, result.membershipVersion()); + assertEquals(3L, result.membershipAuthorityGeneration()); + } + + @Test + void canonicalActiveControlOnlyMemberReturnsExactSnapshotWithoutGameplayOrRoleUpgrade() { + var f = canonicalJoinFixture(); + f.terminal("ALREADY_ACTIVE", 7L, 3L); + f.currentMembership.setGameplayAdmissionAllowed(false); + f.joined.set(true); + when(f.demo.allowPublicJoin()).thenReturn(false); + var result = f.browserJoin(); + assertTrue(result.success()); + assertEquals("ALREADY_ACTIVE", result.outcomeCode()); + assertEquals(7L, result.membershipVersion()); + assertEquals(3L, result.membershipAuthorityGeneration()); + assertFalse(result.gameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"source", "demo", "final-demo", "member", "terminal"}) + void canonicalJoinOutageKeepsTheIntentRetryableAndRecoversTheSameRequest(String stage) { + var f = canonicalJoinFixture(); + RuntimeException unavailable = + new DataAccessResourceFailureException("controlled owner outage"); + switch (stage) { + case "source" -> + when(f.sources.readCurrentSourceSelection(f.scope.tenantId())) + .thenThrow(unavailable) + .thenReturn(f.source); + case "demo" -> + when(f.demos.readCurrent(f.scope.tenantId())).thenThrow(unavailable).thenReturn(f.demo); + case "final-demo" -> + when(f.demos.revalidate(f.demo)).thenThrow(unavailable).thenReturn(f.demo); + case "member" -> + org.mockito.Mockito.doThrow(unavailable) + .doAnswer( + invocation -> + f.joined.get() ? Optional.of(f.currentMembership) : Optional.empty()) + .when(accountTenantMembershipRepository) + .findFreshMembershipForUpdate(f.scope.accountId(), f.scope.tenantId()); + case "terminal" -> + org.mockito.Mockito.doThrow(unavailable) + .doAnswer( + invocation -> { + f.joined.set(true); + return f.committed; + }) + .when(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + default -> throw new AssertionError(stage); + } + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + assertTrue(f.browserJoin().success()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(2)) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); + } + + @Test + void canonicalJoinSourceCheckpointChangeRefusesBeforePolicyBindingOrTransition() { + var f = canonicalJoinFixture(); + when(f.source.matches(f.source.checkpoint())).thenReturn(false); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .bindCanonicalPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(f.terminal); + } + + @ParameterizedTest + @ValueSource(strings = {"CONNECT_SCOPE_INVALID", "AUTH_UNAVAILABLE", "CONNECT_SCOPE_MISMATCH"}) + void canonicalJoinReaderRefusalPrecedesDurableIntentAndAllAuthorityWork(String code) { + var f = canonicalJoinFixture(); + when(f.reader.read(f.scope.accountId(), f.scope.connectScopeId())) + .thenThrow(new AuthenticationException(code, "controlled reader refusal")); + assertEquals(code, assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(accountJoinOperationRepository, f.sources, f.demos, f.terminal); + } + + @ParameterizedTest + @ValueSource(strings = {"ADMISSION_POINTER_UNAVAILABLE", "CONNECT_SCOPE_MISMATCH"}) + void canonicalJoinTargetFailureRetainsTheOriginalIntentWithoutAWrite(String code) { + var f = canonicalJoinFixture(); + org.mockito.Mockito.doThrow(new AuthenticationException(code, "controlled target refusal")) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + assertEquals(code, assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + if (code.equals("CONNECT_SCOPE_MISMATCH")) { + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, code); + } else { + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure(f.requestId, f.scope, f.binding, "UNAVAILABLE", code); + } + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinChangedTargetBetweenStrictReadsIsTerminalWithoutMembershipEffects() { + var f = canonicalJoinFixture(); + var changed = + org.mockito.Mockito.mock(Target.class, org.mockito.AdditionalAnswers.delegatesTo(f.target)); + when(changed.activeWorldEpoch()).thenReturn(2L); + var reads = new java.util.concurrent.atomic.AtomicInteger(); + org.mockito.Mockito.doAnswer( + invocation -> + f.resolve( + invocation.getArgument(0), reads.incrementAndGet() == 1 ? f.target : changed)) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, "CONNECT_SCOPE_MISMATCH"); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.times(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinStrictPublishedSourceOutageCannotUseResolverOnlyAuthority() { + var f = canonicalJoinFixture(); + org.mockito.Mockito.doThrow( + new IllegalStateException("controlled unavailable World ACTIVE source")) + .when(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + assertEquals( + "ADMISSION_POINTER_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"); + verifyNoInteractions(f.terminal); + } + + @ParameterizedTest + @ValueSource(longs = {-1L, 120L}) + void canonicalJoinFutureOrExpiredScopeCannotReachMembershipCommit(long seconds) { + var f = canonicalJoinFixture(); + f.compose( + Clock.fixed( + Instant.parse(f.scope.evaluatedAt()).plusSeconds(seconds), java.time.ZoneOffset.UTC)); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.terminal); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalJoinRefusesAmbientTransactionsBeforeReadingTheCaller(boolean synchronization) { + var f = canonicalJoinFixture(); + try { + if (synchronization) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + assertThrows(IllegalStateException.class, f::browserJoin); + verifyNoInteractions(f.reader, f.targets, f.sources, f.demos, f.terminal); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "too-long"}) + void canonicalJoinRejectsInvalidRequestBeforeScopeOrIntentWork(String request) { + var f = canonicalJoinFixture(); + String id = request.equals("too-long") ? "j".repeat(129) : request; + assertEquals( + request.equals("too-long") ? "INVALID_ARGUMENT" : "CONNECT_SCOPE_INVALID", + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + f.bootstrap, new JoinPublicProductionRequest(f.scope.connectScopeId(), id))) + .getCode()); + verifyNoInteractions(f.reader, accountJoinOperationRepository, f.terminal); + } + + @Test + void canonicalJoinAcceptsTheFull128CharacterRequestIdentity() { + var f = canonicalJoinFixture("j".repeat(128)); + assertTrue(f.browserJoin().success()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); + } + + @Test + void canonicalJoinConflictingRequestDoesNotReplaceOriginalEvidence() { + var f = canonicalJoinFixture(); + when(accountJoinOperationRepository.insertCanonicalIntent(f.requestId, f.scope, f.binding)) + .thenThrow( + new AccountJoinOperationRepository.CanonicalJoinOperationConflictException( + "controlled different caller or selector")); + assertEquals( + "IDEMPOTENCY_CONFLICT", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.sources, f.demos, f.terminal); + } + + @ParameterizedTest + @EnumSource( + value = AccountLifecycleState.class, + names = {"DEACTIVATED_PENDING_DELETE", "SECURITY_LOCKED", "DELETED"}) + void canonicalJoinCurrentAccountLifecycleBlocksAStillLiveBootstrap(AccountLifecycleState state) { + var f = canonicalJoinFixture(); + f.account.setLifecycleState(state); + assertThrows(AuthenticationException.class, f::browserJoin); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinRechecksTheBrowserRegistryAfterTargetReadsBeforeCommit() { + var f = canonicalJoinFixture(); + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(true, false); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalDirectJoinUsesTheSameTerminalOwnerAndUuidTargetWithoutBootstrapSession() + throws Exception { + var f = canonicalJoinFixture(); + var caller = f.directCaller(f.requestId); + f.binding = caller.sessionId(); + org.mockito.Mockito.clearInvocations(sessionService); + var result = + canonicalGameSessionPeer() + .call( + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); + assertTrue(result.success()); + assertEquals(f.scope.tenantId(), result.tenantId()); + verifyNoInteractions(sessionService); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } + + @ParameterizedTest + @ValueSource(strings = {"absent", "namespace", "service"}) + void canonicalDirectJoinRejectsWrongWorkloadBeforeReadingScope(String mismatch) throws Exception { + var f = canonicalJoinFixture(); + var peer = io.grpc.Context.ROOT; + if (!mismatch.equals("absent")) { + String namespace = mismatch.equals("namespace") ? "other" : "test"; + String name = + mismatch.equals("service") ? "world-management-service" : "game-session-service"; + peer = + peer.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + name, namespace, name)); + } + assertEquals( + "AUTH_UNAVAILABLE", + peer.call( + () -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + f.directCaller(f.requestId), + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) + .getCode()); + verifyNoInteractions(f.reader, accountJoinOperationRepository, f.terminal); + } + + @ParameterizedTest + @ValueSource(strings = {"tenant", "realm", "namespace", "scope", "instance"}) + void canonicalDirectJoinRejectsAnyCallerTargetMismatchBeforeIntent(String field) + throws Exception { + var f = canonicalJoinFixture(); + var caller = + new DirectTextCallerContext( + f.scope.accountId(), + field.equals("tenant") ? UUID.randomUUID() : f.scope.tenantId(), + field.equals("realm") ? UUID.randomUUID() : f.scope.realmId(), + field.equals("namespace") ? UUID.randomUUID() : f.scope.playableStateNamespaceId(), + field.equals("scope") ? "ISOLATED" : f.scope.playableStateScope(), + field.equals("instance") ? UUID.randomUUID() : f.scope.gameInstanceId(), + UUID.randomUUID().toString(), + f.requestId); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + canonicalGameSessionPeer() + .call( + () -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) + .getCode()); + verifyNoInteractions(accountJoinOperationRepository, f.terminal); + } + + private CanonicalJoinFixture canonicalJoinFixture() { + return canonicalJoinFixture("canonical-request"); + } + + private CanonicalJoinFixture canonicalJoinFixture(String requestId) { + return new CanonicalJoinFixture(requestId); + } + + private static io.grpc.Context canonicalGameSessionPeer() { + return io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", "test", "game-session-service")); + } + + private final class CanonicalJoinFixture { + private final Account account = new Account(); + private final CanonicalJoinScopeV2 scope; + private final String requestId; + private final String bootstrap; + private final AccountTenantMembership currentMembership = new AccountTenantMembership(); + private final AtomicBoolean joined = new AtomicBoolean(); + private String binding = UUID.randomUUID().toString(); + private final net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader + reader = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader + .class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final Target target = org.mockito.Mockito.mock(Target.class); + private final net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + roster = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .class); + private Target resolvedTarget = target; + private byte[] policyBytes = + "controlled-unit-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); + private final net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository + sources = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.class); + private final net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.SourceSelection + source = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.SourceSelection.class); + private final net.firedevops.firemud.accountservice.repository + .AccountDemoTenantEntitlementRepository + demos = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountDemoTenantEntitlementRepository.class); + private final net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot demo = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot.class); + private final net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository + hosting = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.class); + private final net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver + observer = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver + .class); + private final net.firedevops.firemud.accountservice.service + .AccountCanonicalFirstJoinTerminalCoordinator + terminal = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service + .AccountCanonicalFirstJoinTerminalCoordinator.class); + private final AccountJoinOperationRepository.CanonicalJoinOperationEvidence pending = + org.mockito.Mockito.mock( + AccountJoinOperationRepository.CanonicalJoinOperationEvidence.class); + private final AccountJoinOperationRepository.CanonicalJoinOperationEvidence committed = + org.mockito.Mockito.mock( + AccountJoinOperationRepository.CanonicalJoinOperationEvidence.class); + + private CanonicalJoinFixture(String requestId) { + this.requestId = requestId; + account.setId(11L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findByAccountUuidForUpdate(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + var now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); + scope = + new CanonicalJoinScopeV2( + "controlled-v2-token", + account.getAccountUuid(), + UUID.randomUUID(), + UUID.fromString(REALM_ID), + "tenant", + "demo", + "production", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + UUID.randomUUID(), + 23L, + 17L, + now.toString(), + now.plusSeconds(120).toString()); + bootstrap = + jwtUtil.generateToken( + account.getAccountUuid().toString(), + 300000L, + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + binding)); + when(sessionService.isAccountSessionActive(account.getId(), bootstrap)).thenReturn(true); + when(reader.read(scope.accountId(), scope.connectScopeId())).thenReturn(scope); + when(target.targetNamespace()).thenReturn("test"); + when(target.canonicalTenantId()).thenReturn(scope.tenantId()); + when(target.tenantSlug()).thenReturn(scope.tenantSlug()); + when(target.worldSlug()).thenReturn(scope.worldSlug()); + when(target.realmId()).thenReturn(scope.realmId()); + when(target.realmSlug()).thenReturn(scope.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(scope.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(scope.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(scope.gameInstanceId()); + when(target.canonicalVersionId()).thenReturn(UUID.randomUUID()); + when(target.catalogRevision()).thenReturn(scope.catalogRevision()); + when(target.pointerVersion()).thenReturn(scope.pointerVersion()); + when(target.activeWorldEpoch()).thenReturn(1L); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + when(targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> resolve(invocation.getArgument(0), target)); + when(targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + Target currentTarget = resolvedTarget; + long activeWorldEpoch = currentTarget.activeWorldEpoch(); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(strict); + when(published.currentTarget()).thenReturn(currentTarget); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + when(sourceEvidence.request()).thenReturn(strict); + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication + .PublishedRealmEntryPolicySetEvidence.class); + when(policies.canonicalBytes()).thenReturn(policyBytes); + when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policies); + when(published.sourceEvidence()).thenReturn(sourceEvidence); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + when(world.lifecycleStatus()).thenReturn("ACTIVE"); + when(world.lifecycleEpoch()).thenReturn(activeWorldEpoch); + when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); + when(pending.status()).thenReturn("PENDING"); + when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId)) + .thenReturn(Optional.of(pending)); + when(sources.readCurrentSourceSelection(scope.tenantId())).thenReturn(source); + when(source.kind()) + .thenReturn( + net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + .SourceKind.NON_PAID_DEMO); + when(source.matches(source.checkpoint())).thenReturn(true); + when(demos.readCurrent(scope.tenantId())).thenReturn(demo); + when(demos.revalidate(demo)).thenReturn(demo); + when(demo.gameplayAvailable()).thenReturn(true); + when(demo.allowPublicJoin()).thenReturn(true); + when(demo.entitlementVersion()).thenReturn(1L); + terminal("JOINED", 2L, 1L); + when(accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId())) + .thenAnswer( + invocation -> joined.get() ? Optional.of(currentMembership) : Optional.empty()); + when(terminal.commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(scope), + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull())) + .thenAnswer( + invocation -> { + joined.set(true); + return committed; + }); + service.setAccountBootstrapRosterReadClient(roster); + compose(Clock.fixed(now.plusSeconds(1), java.time.ZoneOffset.UTC)); + } + + private net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + resolve( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + selector, + Target current) { + resolvedTarget = current; + var resolved = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget.class); + var strict = + new net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + current.canonicalVersionId(), + selector.catalogRevision(), + selector.pointerVersion(), + current.activeWorldEpoch()); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(current); + when(resolved.strictSelector()).thenReturn(strict); + return resolved; + } + + private void terminal(String outcome, long version, long generation) { + currentMembership.setId(701L); + currentMembership.setAccount(account); + currentMembership.setTenantUuid(scope.tenantId()); + currentMembership.setTenantProvenanceKind("FRESH_GAME_DESIGN"); + currentMembership.setAuthorityProvenance("EXPLICIT_JOIN"); + currentMembership.setLifecycleState("ACTIVE"); + currentMembership.setGameplayAdmissionAllowed(true); + currentMembership.setMembershipVersion(version); + currentMembership.setMembershipAuthorityGeneration(generation); + when(committed.outcome()).thenReturn(outcome); + when(committed.terminalProof()) + .thenReturn( + new AccountJoinOperationRepository.CanonicalJoinTerminalProof( + "membership-stream", + 1L, + UUID.randomUUID().toString(), + "sha256:" + "a".repeat(64), + outcome.equals("ALREADY_ACTIVE") ? null : UUID.randomUUID(), + outcome.equals("ALREADY_ACTIVE") ? null : "sha256:" + "b".repeat(64), + outcome.equals("ALREADY_ACTIVE") ? null : Instant.now(), + 1L, + 701L, + version, + generation)); + } + + private void compose(Clock clock) { + service.setCanonicalScopeConsumers( + reader, targets, sources, demos, hosting, observer, terminal, "test", clock); + } + + private JoinPublicProductionResult browserJoin() { + return service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(scope.connectScopeId(), requestId)); + } + + private List characters() { + return service.listBootstrapCharacters( + bootstrap, scope.worldSlug(), scope.realmSlug(), scope.connectScopeId()); + } + + private DirectTextCallerContext directCaller(String id) { + return new DirectTextCallerContext( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + UUID.randomUUID().toString(), + id); + } + } + + @Test + void + canonicalBootstrapCharactersReturnsOnlyTheSelectedOwnersActorsSortedWithOwnerReportedLevels() { + var f = canonicalJoinFixture(); + f.joined.set(true); + UUID ada = UUID.randomUUID(), zed = UUID.randomUUID(); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(zed, "Zed", 37), + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(ada, "Ada", 12))); + var actors = f.characters(); + assertEquals( + List.of("Ada", "Zed"), actors.stream().map(value -> value.characterName()).toList()); + assertEquals( + List.of(ada.toString(), zed.toString()), + actors.stream().map(value -> value.characterId()).toList()); + assertEquals(List.of(12, 37), actors.stream().map(value -> value.level()).toList()); + assertTrue( + actors.stream() + .allMatch( + value -> + "SHARED".equals(value.stateScope()) + && "PRESEEDED_ONLY".equals(value.characterCreationPolicy()))); + var target = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + target.capture()); + assertEquals(f.scope.accountId(), target.getValue().selector().canonicalAccountUuid()); + assertEquals(f.scope.tenantId(), target.getValue().selector().canonicalTenantUuid()); + assertEquals(f.scope.realmId(), target.getValue().selector().realmUuid()); + assertEquals( + f.scope.playableStateNamespaceId(), + target.getValue().selector().playableStateNamespaceUuid()); + assertEquals( + f.scope.gameInstanceId(), target.getValue().selector().canonicalGameInstanceUuid()); + assertEquals(f.scope.catalogRevision(), target.getValue().selector().expectedCatalogRevision()); + assertEquals(f.scope.pointerVersion(), target.getValue().selector().expectedPointerVersion()); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.atLeast(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions( + entityManagementClient, accountJoinOperationRepository, accountAuditOutboxRepository); + } + + @Test + void canonicalBootstrapCharactersSelectedScopeDoesNotDependOnUnrelatedLegacyRealmDiscovery() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(gameSessionClient.listGameplayRealms(f.scope.worldSlug())) + .thenThrow(new IllegalStateException("controlled malformed unrelated legacy discovery")); + UUID actor = UUID.randomUUID(); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(actor, "Selected actor", 17))); + assertEquals( + List.of(actor.toString()), + f.characters().stream().map(value -> value.characterId()).toList()); + verifyNoInteractions(gameSessionClient, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersReturnsEmptyOnlyAfterSuccessfulSupportedOwnerRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any())) + .thenReturn(List.of()); + assertTrue(f.characters().isEmpty()); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any()); + verifyNoInteractions( + entityManagementClient, accountJoinOperationRepository, accountAuditOutboxRepository); + } + + @ParameterizedTest + @CsvSource({ + "MISSING,true,JOIN_REQUIRED", + "INACTIVE,true,JOIN_REQUIRED", + "MISSING,false,PUBLIC_PRODUCTION_ADMISSION_DENIED", + "INACTIVE,false,PUBLIC_PRODUCTION_ADMISSION_DENIED" + }) + void canonicalBootstrapCharactersClassifiesPublicMembershipOnlyAfterFreshPolicy( + String lifecycle, boolean open, String code) { + var f = canonicalJoinFixture(); + f.joined.set(!lifecycle.equals("MISSING")); + f.currentMembership.setLifecycleState(lifecycle); + f.currentMembership.setGameplayAdmissionAllowed(false); + when(f.demo.allowPublicJoin()).thenReturn(open); + assertEquals(code, assertThrows(AuthenticationException.class, f::characters).getCode()); + org.mockito.Mockito.verify(f.demos, org.mockito.Mockito.atLeastOnce()).revalidate(f.demo); + verifyNoInteractions( + f.roster, + entityManagementClient, + accountJoinOperationRepository, + accountAuditOutboxRepository); + } + + @Test + void canonicalBootstrapCharactersRejectsActiveControlOnlyMembershipWithoutRepair() { + var f = canonicalJoinFixture(); + f.joined.set(true); + f.currentMembership.setGameplayAdmissionAllowed(false); + assertEquals( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + f.roster, + entityManagementClient, + accountJoinOperationRepository, + accountAuditOutboxRepository); + } + + @Test + void canonicalBootstrapCharactersCannotInterpretBillingOutageAsMissingMembershipOrEmptyRoster() { + var f = canonicalJoinFixture(); + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow( + new DataAccessResourceFailureException("controlled canonical entitlement outage")); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster, entityManagementClient, accountJoinOperationRepository); + } + + @Test + void canonicalBootstrapCharactersRejectsFreshBillingDenialBeforeDisclosure() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.demo.gameplayAvailable()).thenReturn(false); + assertEquals( + "TENANT_BILLING_BLOCKED", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster, entityManagementClient); + } + + @ParameterizedTest + @ValueSource(strings = {"world", "realm"}) + void canonicalBootstrapCharactersRequiresTheExactScopeRoute(String changed) { + var f = canonicalJoinFixture(); + f.joined.set(true); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + f.bootstrap, + changed.equals("world") ? "another-world" : f.scope.worldSlug(), + changed.equals("realm") ? "another-realm" : f.scope.realmSlug(), + f.scope.connectScopeId())) + .getCode()); + verifyNoInteractions(f.roster, entityManagementClient); + } + + @ParameterizedTest + @ValueSource(strings = {"control-ui", "bootstrap-connect-scope"}) + void canonicalBootstrapCharactersRequiresTheBrowserBootstrapCredentialProfile(String audience) { + var f = canonicalJoinFixture(); + String token = + jwtUtil.generateToken( + f.scope.accountId().toString(), + Map.of( + "aud", + audience, + "accountId", + f.scope.accountId().toString(), + "jti", + UUID.randomUUID().toString())); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + token, f.scope.worldSlug(), f.scope.realmSlug(), f.scope.connectScopeId())) + .getCode()); + verifyNoInteractions(f.reader, f.targets, f.roster, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersRejectsInactiveBrowserSessionBeforeTargetOrEntityWork() { + var f = canonicalJoinFixture(); + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)).thenReturn(false); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.reader, f.targets, f.roster, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersPreservesReaderIdentityRefusalBeforeEntityWork() { + var f = canonicalJoinFixture(); + when(f.reader.read(f.scope.accountId(), f.scope.connectScopeId())) + .thenThrow( + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "controlled Account/scope mismatch")); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.targets, f.roster, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersRejectsTargetDriftDuringEntityReadInsteadOfReturningActors() { + var f = canonicalJoinFixture(); + f.joined.set(true); + var changed = + org.mockito.Mockito.mock(Target.class, org.mockito.AdditionalAnswers.delegatesTo(f.target)); + when(changed.activeWorldEpoch()).thenReturn(2L); + AtomicBoolean drift = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> f.resolve(invocation.getArgument(0), drift.get() ? changed : f.target)) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + drift.set(true); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersRechecksMembershipAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + f.currentMembership.setLifecycleState("INACTIVE"); + f.currentMembership.setGameplayAdmissionAllowed(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + assertThrows(AuthenticationException.class, f::characters); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @ParameterizedTest + @ValueSource(strings = {"version", "generation", "membership-id"}) + void canonicalBootstrapCharactersRejectsChangedMembershipSnapshotAfterEntityRead(String changed) { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + switch (changed) { + case "version" -> + f.currentMembership.setMembershipVersion( + f.currentMembership.getMembershipVersion() + 1L); + case "generation" -> + f.currentMembership.setMembershipAuthorityGeneration( + f.currentMembership.getMembershipAuthorityGeneration() + 1L); + case "membership-id" -> f.currentMembership.setId(702L); + default -> throw new AssertionError(changed); + } + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); + assertEquals( + "AUTH_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersRejectsChangedPublishedPolicyCaptureAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + f.policyBytes = + "changed-controlled-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersRechecksCurrentEntitlementAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow( + new DataAccessResourceFailureException("controlled late billing outage")); + when(f.demos.revalidate(f.demo)) + .thenThrow( + new DataAccessResourceFailureException("controlled late billing outage")); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersCannotTranslateEntityOutageIntoSuccessfulEmptyDiscovery() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenThrow(new IllegalStateException("controlled Entity discovery unavailable")); + assertEquals( + "AUTH_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @Test + void canonicalBootstrapCharactersRefusesScopeThatExpiresDuringEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + var time = + new java.util.concurrent.atomic.AtomicReference<>( + Instant.parse(f.scope.evaluatedAt()).plusSeconds(1)); + f.compose( + new Clock() { + @Override + public java.time.ZoneId getZone() { + return java.time.ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return time.get(); + } + }); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + time.set(Instant.parse(f.scope.connectScopeExpiresAt())); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } + + @ParameterizedTest + @ValueSource(strings = {"tenant", "realm", "namespace", "instance", "catalog", "pointer"}) + void canonicalBootstrapCharactersCannotDiscloseForAChangedRetainedTargetField(String field) { + var f = canonicalJoinFixture(); + f.joined.set(true); + switch (field) { + case "tenant" -> when(f.target.canonicalTenantId()).thenReturn(UUID.randomUUID()); + case "realm" -> when(f.target.realmId()).thenReturn(UUID.randomUUID()); + case "namespace" -> when(f.target.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); + case "instance" -> when(f.target.canonicalGameInstanceId()).thenReturn(UUID.randomUUID()); + case "catalog" -> when(f.target.catalogRevision()).thenReturn(f.scope.catalogRevision() + 1L); + case "pointer" -> when(f.target.pointerVersion()).thenReturn(f.scope.pointerVersion() + 1L); + default -> throw new AssertionError(field); + } + assertEquals( + "ADMISSION_POINTER_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster, entityManagementClient); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalBootstrapCharactersRefusesAmbientSqlBeforeCallerOrRemoteRead( + boolean synchronization) { + var f = canonicalJoinFixture(); + try { + if (synchronization) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + assertThrows(IllegalStateException.class, f::characters); + verifyNoInteractions(f.reader, f.targets, f.roster, entityManagementClient); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void canonicalBootstrapCharactersRechecksTheBrowserRegistryAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); + } - assertEquals("Account already exists", exception.getMessage()); + @ParameterizedTest + @CsvSource({"FAILED_PRECONDITION,CONNECT_SCOPE_MISMATCH", "UNAVAILABLE,AUTH_UNAVAILABLE"}) + void canonicalBootstrapCharactersPreservesEntityCurrentnessAndUnavailableFailureBoundaries( + String status, String code) { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenThrow( + io.grpc.Status.fromCode(io.grpc.Status.Code.valueOf(status)).asRuntimeException()); + assertEquals(code, assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountAuditOutboxRepository, entityManagementClient); } + /** + * ISOLATED positive discovery remains unfinished; a public V2 carrier cannot select its policy. + */ @Test - void createAccountMapsSpringDataIntegrityConflict() { - CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) - .thenThrow(new org.springframework.dao.DataIntegrityViolationException("duplicate")); - - AccountAlreadyExistsException exception = - assertThrows(AccountAlreadyExistsException.class, () -> service.createAccount(request)); + void canonicalBootstrapCharactersExplicitlyRefusesUnsupportedIsolatedScope() { + var f = canonicalJoinFixture(); + var isolated = + new CanonicalJoinScopeV2( + f.scope.connectScopeId(), + f.scope.accountId(), + f.scope.tenantId(), + f.scope.realmId(), + f.scope.tenantSlug(), + f.scope.worldSlug(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + "ISOLATED", + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion(), + f.scope.evaluatedAt(), + f.scope.connectScopeExpiresAt()); + when(f.reader.read(f.scope.accountId(), f.scope.connectScopeId())).thenReturn(isolated); + assertEquals( + "REALM_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.targets, f.roster, entityManagementClient); + } - assertEquals("Account already exists", exception.getMessage()); + /** + * Denial proof only: PLAYER_CREATED/AUTO/private/ISOLATED positive branches remain unfinished. + */ + @ParameterizedTest + @ValueSource(strings = {"PLAYER_CREATED", "AUTO_PROVISIONED"}) + void canonicalBootstrapCharactersDoesNotPretendUnsupportedPolicyIsAnEmptyRoster(String policy) { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.target.characterCreationPolicy()).thenReturn(policy); + assertThrows(AuthenticationException.class, f::characters); + verifyNoInteractions(f.roster, entityManagementClient); } @Test @@ -1086,6 +2524,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { @Test void issuePlayerBootstrapReturnsShortLivedToken() { + composeOrdinaryBootstrapWorldDiscovery(); Account account = new Account(); account.setId(7L); setPersistedAuthenticationIdentity(account); @@ -1112,10 +2551,13 @@ void issuePlayerBootstrapReturnsShortLivedToken() { assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertFalse(claims.containsKey("tenantId")); assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); - org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .isAccountSessionActive( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString()); + when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); + var worlds = service.listBootstrapWorlds(result.bootstrapToken()); + assertEquals("demo", worlds.getFirst().worldSlug()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(3)) + .findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(2)) + .isAccountSessionActive(7L, result.bootstrapToken()); verifyNoInteractions(accountEmailLoginChallengeRepository); } @@ -1196,6 +2638,375 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { .storeAccountSession(7L, result.bootstrapToken(), 300000L); } + private static java.util.stream.Stream + invalidBootstrapAccountClaims() { + String valid = "10000000-0000-4000-8000-00000000000a"; + return java.util.stream.Stream.of( + org.junit.jupiter.params.provider.Arguments.of("11", "11"), + org.junit.jupiter.params.provider.Arguments.of((String) null, valid), + org.junit.jupiter.params.provider.Arguments.of( + valid.toUpperCase(java.util.Locale.ROOT), valid), + org.junit.jupiter.params.provider.Arguments.of(" " + valid, valid), + org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), + org.junit.jupiter.params.provider.Arguments.of(valid, ""), + org.junit.jupiter.params.provider.Arguments.of(valid, 11L), + org.junit.jupiter.params.provider.Arguments.of(valid, "11"), + org.junit.jupiter.params.provider.Arguments.of( + valid, "00000000-0000-0000-0000-000000000000"), + org.junit.jupiter.params.provider.Arguments.of( + "00000000-0000-0000-0000-000000000000", valid), + org.junit.jupiter.params.provider.Arguments.of(valid, "not-a-uuid"), + org.junit.jupiter.params.provider.Arguments.of( + valid, valid.toUpperCase(java.util.Locale.ROOT)), + org.junit.jupiter.params.provider.Arguments.of(valid, " " + valid), + org.junit.jupiter.params.provider.Arguments.of( + valid, "10000000-0000-4000-8000-000000000002")); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.MethodSource("invalidBootstrapAccountClaims") + void bootstrapReaderRejectsNonUuidOrContradictoryIdentityBeforeOwnerOrSessionUse( + String subject, Object accountClaim) { + composeOrdinaryBootstrapWorldDiscovery(); + Map claims = new java.util.HashMap<>(); + claims.put("aud", "player-bootstrap"); + if (accountClaim != null) { + claims.put("accountId", accountClaim); + } + String token = new JwtUtil(JWT_SECRET, 300000L).generateToken(subject, claims); + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); + + assertEquals("CONNECT_CONTEXT_INVALID", denied.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "wrong-owner-uuid", "unavailable"}) + void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) { + composeOrdinaryBootstrapWorldDiscovery(); + UUID uuid = UUID.fromString("10000000-0000-4000-8000-000000000001"); + if (failure.equals("unavailable")) { + when(accountRepository.findByAccountUuid(uuid)) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException("private detail")); + } else if (failure.equals("wrong-owner-uuid")) { + Account owner = new Account(); + owner.setId(11L); + owner.setAccountUuid(UUID.randomUUID()); + owner.setAccountUuidSourceNumericId(11L); + owner.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(accountRepository.findByAccountUuid(uuid)).thenReturn(Optional.of(owner)); + } + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + uuid.toString(), Map.of("aud", "player-bootstrap", "accountId", uuid.toString())); + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); + + assertEquals("AUTH_UNAVAILABLE", denied.getCode()); + assertEquals("Account authority is unavailable", denied.getMessage()); + verifyNoInteractions(sessionService); + } + + @Test + void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { + composeOrdinaryBootstrapWorldDiscovery(); + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String uuid = account.getAccountUuid().toString(); + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(uuid, Map.of("aud", "player-bootstrap", "accountId", uuid)); + when(sessionService.isAccountSessionActive(11L, token)).thenReturn(true); + + assertFalse(service.listBootstrapWorlds(token).isEmpty()); + + org.mockito.InOrder reads = org.mockito.Mockito.inOrder(accountRepository, sessionService); + reads.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + reads.verify(sessionService).isAccountSessionActive(11L, token); + } + + @Test + void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { + composeOrdinaryBootstrapWorldDiscovery(); + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String accountUuid = account.getAccountUuid().toString(); + String bootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, () -> service.listBootstrapWorlds(bootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + assertEquals("Bootstrap token expired", ex.getMessage()); + org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); + } + + @ParameterizedTest + @ValueSource( + strings = { + "not-a-uuid", + "abc", + "0", + "00000000-0000-0000-0000-000000000000", + "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", + " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " + }) + void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + REALM_ID, + Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + } + + @Test + void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + } + + @Test + void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { + JwtUtil jwtUtil = org.mockito.Mockito.mock(JwtUtil.class); + IllegalStateException parserFailure = new IllegalStateException("boom"); + when(jwtUtil.parseToken("boom-token")).thenThrow(parserFailure); + this.jwtUtil = jwtUtil; + service = + new AccountServiceImpl( + accountRepository, + accountAuthorityGenerationRepository, + accountAuthoritySourceEvidenceRepository, + accountAuthorityOutboxRepository, + accountPasswordResetOperationRepository, + accountLogoutAllOperationRepository, + accountSecurityStateOperationRepository, + accountPasswordResetDraftSourceChangeRepository, + accountAuditOutboxRepository, + accountJoinOperationRepository, + accountEmailLoginChallengeRepository, + accountRealmAccessGrantRepository, + accountTenantMembershipRepository, + Mappers.getMapper(AccountMapper.class), + profileRepository, + profileMapper, + paymentTransactionRepository, + retainedSubscriptionEvidenceRepository, + externalAccountRepository, + passwordResetTokenRepository, + emailVerificationTokenRepository, + notificationService, + emailService, + mailProperties, + tokenProperties, + jwtAuthProperties, + jwtUtil, + sessionService, + transactionManager); + + composeOrdinaryBootstrapWorldDiscovery(); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, () -> service.listBootstrapWorlds("boom-token")); + + assertEquals("AUTH_UNAVAILABLE", ex.getCode()); + assertSame(parserFailure, ex.getCause()); + verifyNoInteractions( + accountRepository, + sessionService, + accountTenantMembershipRepository, + accountConnectScopeRepository, + accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_SCOPE_INVALID", + "CONNECT_SCOPE_MISMATCH", + "ADMISSION_POINTER_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "AUTH_UNAVAILABLE" + }) + void bootstrapRealmFacadePreservesCanonicalTargetAndPolicyRefusal(String code) { + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + var refusal = new AuthenticationException(code, "controlled current canonical source refusal"); + when(owner.listRealmScopes("bootstrap", "demo")).thenThrow(refusal); + assertSame( + refusal, + assertThrows( + AuthenticationException.class, () -> service.listBootstrapRealms("bootstrap", "demo"))); + verifyNoInteractions( + gameSessionClient, + accountTenantMembershipRepository, + accountRealmAccessGrantRepository, + accountConnectScopeRepository); + } + + @Test + void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceLeaveTransactionsToCanonicalOwners() + throws Exception { + for (var method : + List.of( + AccountServiceImpl.class.getMethod("listBootstrapRealms", String.class, String.class), + AccountServiceImpl.class.getMethod( + "issueDirectTextConnectScope", + DirectTextCallerContext.class, + DirectTextJoinTarget.class), + AccountServiceImpl.class.getMethod( + "joinPublicProduction", String.class, JoinPublicProductionRequest.class), + AccountServiceImpl.class.getMethod( + "listBootstrapCharacters", + String.class, + String.class, + String.class, + String.class))) { + assertNull(method.getAnnotation(Transactional.class)); + } + } + + @Test + void canonicalScopeReaderRejectsRetiredNumericSignedCarrierBeforeScopeLookup() { + var reader = + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwtUtil, accountConnectScopeRepository, transactionManager, Clock.systemUTC()); + String numeric = + jwtUtil.generateToken( + "11", 120000L, Map.of("aud", "bootstrap-connect-scope", "accountId", "11")); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, () -> reader.read(UUID.randomUUID(), numeric)) + .getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @ParameterizedTest + @ValueSource( + strings = { + "account", + "tenant", + "realm", + "namespace", + "instance", + "catalog", + "pointer", + "target-class", + "version", + "audience", + "time", + "jti" + }) + void canonicalScopeReaderRejectsMalformedSignedAuthorityBeforeRetainedLookup(String field) { + UUID account = UUID.randomUUID(); + Instant now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); + Map claims = new java.util.HashMap<>(); + claims.put("aud", "bootstrap-connect-scope"); + claims.put("accountId", account.toString()); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("targetClass", "PUBLIC_PRODUCTION"); + claims.put("scopeDigestVersion", 2); + claims.put("tenantId", UUID.randomUUID().toString()); + claims.put("realmId", REALM_ID); + claims.put("tenantSlug", "tenant"); + claims.put("worldSlug", "demo"); + claims.put("realmSlug", "production"); + claims.put("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID); + claims.put("playableStateScope", "SHARED"); + claims.put("gameInstanceId", UUID.randomUUID().toString()); + claims.put("catalogRevision", 23L); + claims.put("pointerVersion", 17L); + claims.put("evaluatedAt", now.toString()); + claims.put("connectScopeExpiresAt", now.plusSeconds(120).toString()); + switch (field) { + case "account" -> claims.put("accountId", UUID.randomUUID().toString()); + case "tenant" -> claims.put("tenantId", "7"); + case "realm" -> claims.put("realmId", "not-a-uuid"); + case "namespace" -> claims.put("playableStateNamespaceId", "not-a-uuid"); + case "instance" -> claims.put("gameInstanceId", "44"); + case "catalog" -> claims.put("catalogRevision", 0L); + case "pointer" -> claims.put("pointerVersion", -1L); + case "target-class" -> claims.put("targetClass", "PRIVATE"); + case "version" -> claims.put("scopeDigestVersion", 1); + case "audience" -> claims.put("aud", List.of("bootstrap-connect-scope", "control-ui")); + case "time" -> claims.put("evaluatedAt", now.plusSeconds(60).toString()); + case "jti" -> claims.remove("jti"); + default -> throw new AssertionError(field); + } + String token = jwtUtil.generateToken(account.toString(), now.plusSeconds(120), claims); + var reader = + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwtUtil, + accountConnectScopeRepository, + transactionManager, + Clock.fixed(now.plusSeconds(1), java.time.ZoneOffset.UTC)); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, () -> reader.read(account, token)).getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + @Test void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); @@ -1376,6 +3187,280 @@ void getTenantEntitlementsForRuntimeFailsClosedBeforeReadingLegacyEvidence() { verifyNoInteractions(retainedSubscriptionEvidenceRepository); } + @Test + void directScopeFacadePublishesTheExactCanonicalOwnersArtifactWithoutReminting() { + var f = canonicalJoinFixture(); + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + var retained = org.mockito.Mockito.mock(RealmScope.class); + when(retained.scope()).thenReturn(f.scope); + var caller = f.directCaller(f.requestId); + var target = + new DirectTextJoinTarget( + f.scope.tenantId(), + f.scope.realmId(), + f.scope.worldSlug(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + f.scope.playableStateScope(), + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion()); + when(owner.issueDirectTextScope(caller, target)).thenReturn(retained); + service.setCanonicalPublicRealmScopeOwner(owner); + var result = service.issueDirectTextConnectScope(caller, target); + assertEquals(f.scope.connectScopeId(), result.connectScopeId()); + assertEquals(f.scope.evaluatedAt(), result.evaluatedAt()); + assertEquals(f.scope.connectScopeExpiresAt(), result.connectScopeExpiresAt()); + org.mockito.Mockito.verify(owner).issueDirectTextScope(caller, target); + verifyNoInteractions( + accountConnectScopeRepository, + sessionService, + f.sources, + accountJoinOperationRepository, + accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_SCOPE_INVALID", + "CONNECT_SCOPE_MISMATCH", + "AUTH_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "TENANT_BILLING_BLOCKED", + "ADMISSION_POINTER_UNAVAILABLE" + }) + void directScopeFacadePreservesCanonicalAuthenticationCurrentnessAndBillingRefusal(String code) { + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + var refusal = new AuthenticationException(code, "controlled canonical scope owner refusal"); + when(owner.issueDirectTextScope( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenThrow(refusal); + var f = canonicalJoinFixture(); + assertSame( + refusal, + assertThrows( + AuthenticationException.class, + () -> + service.issueDirectTextConnectScope( + f.directCaller(f.requestId), + new DirectTextJoinTarget( + f.scope.tenantId(), + f.scope.realmId(), + f.scope.worldSlug(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + f.scope.playableStateScope(), + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion())))); + verifyNoInteractions( + accountConnectScopeRepository, + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); + } + + @Test + void directScopeWithoutCanonicalCompositionRefusesBeforeLegacySources() { + assertEquals( + "AUTH_UNAVAILABLE", + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(null, null)) + .getCode()); + verifyNoInteractions(accountRepository, gameSessionClient, accountConnectScopeRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"malformed", "", "numeric-signed"}) + void issueConnectTokenRejectsInvalidScopeWithoutIssuanceOrReplayMutation(String artifact) { + var f = canonicalJoinFixture(); + service.setCanonicalScopeConsumers( + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwtUtil, accountConnectScopeRepository, transactionManager, Clock.systemUTC()), + f.targets, + f.sources, + f.demos, + f.hosting, + f.observer, + f.terminal, + "test", + Clock.systemUTC()); + String token = + artifact.equals("numeric-signed") + ? jwtUtil.generateToken( + "11", Map.of("aud", "bootstrap-connect-scope", "accountId", "11")) + : artifact; + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken(f.bootstrap, new ConnectTokenRequest(token, "held"))) + .getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + 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.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void issueConnectTokenValidatesCanonicalScopeThenKeepsIssuerHeldWithoutReplayOrSessionEffects() { + var f = canonicalJoinFixture(); + assertEquals( + "AUTH_UNAVAILABLE", + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + f.bootstrap, + new ConnectTokenRequest(f.scope.connectScopeId(), "held-issuer"))) + .getCode()); + org.mockito.Mockito.verify(f.reader).read(f.scope.accountId(), f.scope.connectScopeId()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + 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.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyLong()); + 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()); + verifyNoInteractions( + accountTenantMembershipRepository, + accountAuditOutboxRepository, + f.targets, + f.sources, + f.demos, + f.hosting, + f.observer, + f.terminal); + } + + @Test + void listBootstrapWorldsReadsFreshEntitlementsOncePerCanonicalTenantPerInvocation() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + UUID demoTenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID sandboxTenant = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var sourceTargets = + List.of( + publicDiscoveryTarget(sandboxTenant, "sandbox", "Sandbox World"), + publicDiscoveryTarget(demoTenant, "demo", "Demo World")); + var discovery = composeCanonicalWorldDiscovery(sourceTargets); + var evaluatedAt = Instant.now().minusSeconds(1); + when(discovery.entitlements().evaluate(demoTenant)) + .thenReturn(publicDiscoveryEntitlement(demoTenant, true, evaluatedAt)); + when(discovery.entitlements().evaluate(sandboxTenant)) + .thenReturn(publicDiscoveryEntitlement(sandboxTenant, true, evaluatedAt)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + + var firstCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + var secondCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + var expectedWorlds = + List.of( + new BootstrapWorldDto("demo", "Demo World"), + new BootstrapWorldDto("sandbox", "Sandbox World")); + assertEquals(expectedWorlds, firstCall); + assertEquals(expectedWorlds, secondCall); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) + .evaluate(demoTenant); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) + .evaluate(sandboxTenant); + org.mockito.Mockito.verify(discovery.targets(), org.mockito.Mockito.times(4)) + .listVisiblePublicProductionAdmissionTargets(org.mockito.ArgumentMatchers.any(UUID.class)); + } + + @Test + void listBootstrapWorldsFiltersGameplayUnavailableTenantAndFailsWhenEntitlementIsUnavailable() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + UUID demoTenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID sandboxTenant = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var sourceTargets = + List.of( + publicDiscoveryTarget(demoTenant, "demo", "Demo World"), + publicDiscoveryTarget(sandboxTenant, "sandbox", "Sandbox World")); + var discovery = composeCanonicalWorldDiscovery(sourceTargets); + var evaluatedAt = Instant.now().minusSeconds(1); + when(discovery.entitlements().evaluate(demoTenant)) + .thenReturn(publicDiscoveryEntitlement(demoTenant, true, evaluatedAt)) + .thenReturn(publicDiscoveryEntitlement(demoTenant, true, evaluatedAt)) + .thenThrow( + new AccountPublicBootstrapEntitlementOwner.UnavailableException( + new IllegalStateException("controlled current-source failure"))); + when(discovery.entitlements().evaluate(sandboxTenant)) + .thenReturn(publicDiscoveryEntitlement(sandboxTenant, false, evaluatedAt)) + .thenThrow( + new AccountPublicBootstrapEntitlementOwner.UnavailableException( + new IllegalStateException("controlled current-source failure"))); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + + var worldsWithUnavailableTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + assertEquals( + java.util.List.of("demo"), + worldsWithUnavailableTenant.stream().map(world -> world.worldSlug()).toList()); + AuthenticationException unavailableSandbox = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableSandbox.getCode()); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(3)) + .evaluate(demoTenant); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) + .evaluate(sandboxTenant); + } + + @Test + void bootstrapPublicRealmFacadeDoesNotFallBackToPrivateGrantOrNumericDiscovery() { + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + when(owner.listRealmScopes("bootstrap", "demo")).thenReturn(List.of()); + assertTrue(service.listBootstrapRealms("bootstrap", "demo").isEmpty()); + verifyNoInteractions( + gameSessionClient, + accountRealmAccessGrantRepository, + accountTenantMembershipRepository, + accountConnectScopeRepository); + } + @Test void grantRealmAccessUpsertsRuntimeGrant() { Account account = new Account(); @@ -2433,6 +4518,63 @@ private enum InvalidAuthenticationIdentity { CONTRADICTORY_SOURCE_ROW } + private void composeOrdinaryBootstrapWorldDiscovery() { + UUID tenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var fixture = + composeCanonicalWorldDiscovery( + List.of(publicDiscoveryTarget(tenant, "demo", "Demo World"))); + when(fixture.entitlements().evaluate(tenant)) + .thenReturn(publicDiscoveryEntitlement(tenant, true, Instant.now().minusSeconds(1))); + } + + private record CanonicalWorldDiscoveryFixture( + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountPublicBootstrapEntitlementOwner entitlements) {} + + private CanonicalWorldDiscoveryFixture composeCanonicalWorldDiscovery(List targets) { + CanonicalGameplayAdmissionDecisionReadClient targetReader = + org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + var collection = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets + .class); + when(collection.targets()).thenReturn(targets); + when(targetReader.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any(UUID.class))) + .thenReturn(collection); + AccountPublicBootstrapEntitlementOwner entitlements = + org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); + var callerVerifier = + new AccountPlayerBootstrapCallerVerifier(jwtUtil, accountRepository, sessionService); + service.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner( + callerVerifier, targetReader, entitlements, Clock.systemUTC())); + return new CanonicalWorldDiscoveryFixture(targetReader, entitlements); + } + + private static Target publicDiscoveryTarget(UUID tenantId, String worldSlug, String displayName) { + Target target = org.mockito.Mockito.mock(Target.class); + when(target.canonicalTenantId()).thenReturn(tenantId); + when(target.worldSlug()).thenReturn(worldSlug); + when(target.worldDisplayName()).thenReturn(displayName); + return target; + } + + private static AccountPublicBootstrapEntitlementOwner.Evaluation publicDiscoveryEntitlement( + UUID tenantId, boolean gameplayAvailable, Instant evaluatedAt) { + return new AccountPublicBootstrapEntitlementOwner.Evaluation( + tenantId, + net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + .SourceKind.NON_PAID_DEMO, + gameplayAvailable, + false, + 1L, + 1L, + evaluatedAt, + evaluatedAt.plusSeconds(30)); + } + private static String hash(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java new file mode 100644 index 0000000000..ced10986f5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -0,0 +1,588 @@ +package net.firedevops.firemud.common.account.authority; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +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.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account's PUBLIC_PRODUCTION SHARED PRESEEDED PLAYER_ADMISSION variant of the existing runtime + * evidence contract. Content validation is not source authentication or an admission grant. + * + *

The owner must derive this value from its final Account transaction and protected target read. + * Target source references name that complete read; they hold no World lock through later use. + * Decoding validates content only and cannot promote caller-supplied data to source authority. + */ +public final class RuntimePlayerAdmissionEntitlementEvidence { + public static final String SCHEMA = RuntimeTenantOperationEntitlementEvidence.SCHEMA; + public static final String VARIANT = "PLAYER_ADMISSION"; + public static final int MAX_CANONICAL_BYTES = 256 * 1024; + public static final int MAX_CONNECT_SCOPE_CHARS = 16384; + private static final JsonMapper JSON = + JsonMapper.builder( + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(16) + .maxStringLength(65536) + .maxNumberLength(19) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set TARGET_FIELDS = + Set.of( + "targetClass", + "characterCreationPolicy", + "targetNamespace", + "tenantId", + "tenantSlug", + "worldSlug", + "realmId", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "canonicalVersionId", + "catalogRevision", + "pointerVersion", + "activeWorldEpoch", + "evaluatedAt", + "connectScopeExpiresAt"); + private static final Set FACT_FIELDS = + Set.of( + "sourceKind", + "subscriptionStatus", + "provisioningStatus", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "entitlementVersion", + "tenantBillingSequence", + "tenantAuthorityGeneration"); + private static final Set SOURCE_FIELDS = + Set.of( + "callerTokenJti", + "callerTokenExpiresAt", + "paidReceiptValidUntil", + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "callerContextId", + "callerOperationId", + "scopeDigest", + "entitlementSourceDigest", + "admissionPointerSnapshotDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest", + "worldCaptureId", + "worldRowVersion"); + private final Snapshot membership; + private final byte[] canonicalBytes; + + private RuntimePlayerAdmissionEntitlementEvidence(Snapshot membership, byte[] canonicalBytes) { + this.membership = membership; + this.canonicalBytes = canonicalBytes.clone(); + } + + /** Content-only construction; production source provenance belongs to the Account owner. */ + public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( + UUID requestId, + String callerWorkload, + String verifiedConnectScopeId, + Snapshot membership, + Map target, + Map facts, + Map source, + Instant evaluatedAt) { + Objects.requireNonNull(membership); + RuntimeMembershipAuthorityEvidenceValidator.validate(membership); + requireUuid(membership.accountId()); + requireUuid(membership.tenantId()); + if (!membership.authorityTuple().privateRealmGrantVersions().isEmpty()) + throw invalid("Public player evidence cannot carry private grant authority"); + if (!"firemud-account-service".equals(membership.issuerId())) + throw invalid("Canonical Account issuer required"); + requireUuid(requestId.toString()); + var peer = + GrpcPeerIdentity.parseUri(callerWorkload) + .filter( + value -> + value.uri().equals(callerWorkload) + && "game-session-service".equals(value.service())) + .orElseThrow(() -> invalid("Exact Game Session caller required")); + if (verifiedConnectScopeId == null + || verifiedConnectScopeId.isBlank() + || verifiedConnectScopeId.length() > MAX_CONNECT_SCOPE_CHARS) + throw invalid("Verified connect scope required"); + exact(target, TARGET_FIELDS); + exact(facts, FACT_FIELDS); + exact(source, SOURCE_FIELDS); + if (!"PUBLIC_PRODUCTION".equals(target.get("targetClass")) + || !"PRESEEDED_ONLY".equals(target.get("characterCreationPolicy")) + || !peer.namespace().equals(target.get("targetNamespace")) + || !membership.tenantId().equals(target.get("tenantId")) + || !"SHARED".equals(target.get("playableStateScope"))) + throw invalid("Exact public SHARED tenant target required"); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "canonicalVersionId")) requireUuid(text(target.get(key))); + for (String key : List.of("tenantSlug", "worldSlug", "realmSlug")) + if (!text(target.get(key)).matches("[a-z0-9]+(?:-[a-z0-9]+)*")) + throw invalid("Canonical slug required"); + for (String key : List.of("catalogRevision", "pointerVersion", "activeWorldEpoch")) + positive(target.get(key)); + Instant scopeTime = instant(target.get("evaluatedAt")); + Instant scopeExpiry = instant(target.get("connectScopeExpiresAt")); + if (!evaluatedAt.isAfter(Instant.EPOCH) + || evaluatedAt.isBefore(scopeTime) + || !evaluatedAt.isBefore(scopeExpiry)) throw invalid("Scope is not current at evaluation"); + validateFacts(facts, membership); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + requireUuid(text(source.get(key))); + for (String key : + List.of("callerTokenSha256", "callerRegistryRecordSha256", "callerCommitProofSha256")) + if (!text(source.get(key)).matches("[0-9a-f]{64}")) throw invalid("Source SHA-256 required"); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "worldLifecycleDigest", + "publishedPolicySetDigest", + "gameSessionOwnerProofDigest")) + if (!text(source.get(key)).matches("sha256:[0-9a-f]{64}")) + throw invalid("Source digest required"); + for (String key : List.of("admissionPointerSnapshotDigest")) + if (!text(source.get(key)).matches("[0-9a-f]{64}")) + throw invalid("Canonical target source digest required"); + if (!text(source.get("worldRowVersion")).matches("0|[1-9][0-9]{0,18}") + || Long.parseLong(text(source.get("worldRowVersion"))) < 0) + throw invalid("World row version required"); + Instant validUntil = instant(source.get("callerTokenExpiresAt")); + if (scopeExpiry.isBefore(validUntil)) validUntil = scopeExpiry; + if ("PAID_HOSTING".equals(facts.get("sourceKind"))) { + Instant providerDeadline = instant(source.get("paidReceiptValidUntil")); + if (providerDeadline.isBefore(validUntil)) validUntil = providerDeadline; + } else if (source.get("paidReceiptValidUntil") != null) { + throw invalid("Demo evidence cannot assert a paid receipt deadline"); + } + if (!evaluatedAt.isBefore(validUntil)) throw invalid("Player source validity expired"); + Map fields = new LinkedHashMap<>(); + fields.put("schema", SCHEMA); + fields.put("variant", VARIANT); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("issuer", membership.issuerId()); + fields.put("tenantId", membership.tenantId()); + fields.put("callerAccountId", membership.accountId()); + fields.put("callerWorkload", callerWorkload); + fields.put("verifiedConnectScopeId", verifiedConnectScopeId); + fields.put("target", target); + fields.putAll(facts); + fields.put("membershipExists", membership.membershipExists()); + fields.put("membershipLifecycleState", membership.membershipLifecycleState()); + fields.put("gameplayAdmissionAllowed", membership.gameplayAdmissionAllowed()); + fields.put("membershipVersion", membership.membershipVersion()); + fields.put("membershipAuthorityGeneration", membership.membershipAuthorityGeneration()); + fields.put("roles", membership.roles()); + fields.put("issuanceFence", membership.issuanceFence()); + fields.put("authorityTuple", tuple(membership)); + fields.put( + "outboxCheckpoints", + membership.checkpoints().stream() + .map( + checkpoint -> { + Map entry = new LinkedHashMap<>(); + entry.put("outboxStreamKey", checkpoint.outboxStreamKey()); + entry.put("outboxSequence", checkpoint.outboxSequence()); + membership.sourceEvidence().stream() + .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .findFirst() + .ifPresent( + event -> { + entry.put("sourceEventId", event.eventId()); + entry.put("sourceEventDigest", event.eventDigest()); + }); + return entry; + }) + .toList()); + fields.put("authoritySourceEvidence", membership.sourceEvidence()); + fields.put("sourceReferences", source); + fields.put("validUntil", validUntil.toString()); + // The committed-input identity excludes the request and evaluation time. Source references + // include the actual caller issuance, retained scope, billing and protected target captures. + String snapshotIdentity = digest(fields); + fields.put("snapshotIdentity", snapshotIdentity); + fields.put("requestId", requestId.toString()); + fields.put("evaluatedAt", evaluatedAt.toString()); + fields.put( + "evaluationIdentity", + digest( + Map.of( + "snapshotIdentity", + snapshotIdentity, + "requestId", + requestId.toString(), + "callerWorkload", + callerWorkload, + "evaluatedAt", + evaluatedAt.toString()))); + byte[] bytes = canonical(fields); + if (bytes.length > MAX_CANONICAL_BYTES) throw invalid("Player evidence exceeds size bound"); + return new RuntimePlayerAdmissionEntitlementEvidence(membership, bytes); + } + + /** Strict content decoder only; authenticated transport and Account sources remain mandatory. */ + public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) + throw invalid("Player evidence is absent or exceeds size bound"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map fields = JSON.readValue(json, new TypeReference<>() {}); + Map authority = object(fields.get("authorityTuple")); + Set requiredTuple = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + if (!authority.keySet().containsAll(requiredTuple) + || authority.keySet().stream() + .anyMatch( + k -> + !requiredTuple.contains(k) + && !Set.of("accountSecurityCutoff", "tenantBillingCutoff").contains(k)) + || !list(authority.get("privateRealmGrantVersions")).isEmpty()) + throw invalid("Closed public authority tuple required"); + Optional accountCutoff = + Optional.empty(); + if (authority.containsKey("accountSecurityCutoff")) { + var cutoff = object(authority.get("accountSecurityCutoff")); + exact(cutoff, Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence")); + accountCutoff = + Optional.of( + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + text(cutoff.get("accountAuthorityGeneration")), + text(cutoff.get("outboxStreamKey")), + text(cutoff.get("outboxSequence")))); + } + Map tenantCutoffs = + new LinkedHashMap<>(); + object(authority.get("tenantBillingCutoff")) + .forEach( + (tenant, raw) -> { + var cutoff = object(raw); + exact( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence")); + tenantCutoffs.put( + tenant, + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + text(cutoff.get("tenantAuthorityGeneration")), + text(cutoff.get("tenantBillingSequence")), + text(cutoff.get("outboxStreamKey")), text(cutoff.get("outboxSequence")))); + }); + var tuple = + new MembershipAuthorityEventV1Codec.AuthorityTuple( + text(authority.get("issuerAuthGeneration")), + text(authority.get("accountAuthorityGeneration")), + strings(authority.get("tenantAuthorityGeneration")), + strings(authority.get("membershipAuthorityGeneration")), + List.of(), + accountCutoff, + Optional.of(tenantCutoffs)); + var checkpoints = + list(fields.get("outboxCheckpoints")).stream() + .map( + raw -> { + var checkpoint = object(raw); + String stream = text(checkpoint.get("outboxStreamKey")); + String sequence = text(checkpoint.get("outboxSequence")); + return new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + stream, sequence); + }) + .toList(); + var events = + list(fields.get("authoritySourceEvidence")).stream() + .map( + raw -> { + var event = object(raw); + exact( + event, + Set.of( + "outboxStreamKey", + "outboxSequence", + "eventId", + "eventDigest", + "canonicalEventJson")); + return new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + text(event.get("outboxStreamKey")), + text(event.get("outboxSequence")), + text(event.get("eventId")), + text(event.get("eventDigest")), + text(event.get("canonicalEventJson"))); + }) + .toList(); + Snapshot membership = + new Snapshot( + text(fields.get("issuer")), + text(fields.get("callerAccountId")), + text(fields.get("tenantId")), + bool(fields.get("membershipExists")), + text(fields.get("membershipLifecycleState")), + bool(fields.get("gameplayAdmissionAllowed")), + strings(fields.get("membershipVersion")), + text(fields.get("membershipAuthorityGeneration")), + list(fields.get("roles")).stream() + .map(RuntimePlayerAdmissionEntitlementEvidence::text) + .toList(), + tuple, + text(fields.get("issuanceFence")), + checkpoints, + events); + Map facts = new LinkedHashMap<>(); + FACT_FIELDS.forEach(key -> facts.put(key, fields.get(key))); + var rebuilt = + fromOwnerEvaluation( + UUID.fromString(text(fields.get("requestId"))), + text(fields.get("callerWorkload")), + text(fields.get("verifiedConnectScopeId")), + membership, + object(fields.get("target")), + facts, + object(fields.get("sourceReferences")), + instant(fields.get("evaluatedAt"))); + if (!Arrays.equals(bytes, rebuilt.canonicalBytes)) + throw invalid("Player evidence must be the exact closed canonical value"); + return rebuilt; + } catch (CharacterCodingException failure) { + throw invalid("Player evidence requires strict UTF-8"); + } catch (RuntimeException failure) { + throw invalid("Invalid canonical player evidence"); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid("Object required"); + Map result = new LinkedHashMap<>(); + map.forEach((key, member) -> result.put(text(key), member)); + return result; + } + + private static Map strings(Object value) { + Map result = new LinkedHashMap<>(); + object(value).forEach((key, member) -> result.put(key, text(member))); + return result; + } + + private static List list(Object value) { + if (!(value instanceof List list) || list.size() > 16) + throw invalid("Bounded list required"); + return list; + } + + private static boolean bool(Object value) { + if (!(value instanceof Boolean flag)) throw invalid("Boolean required"); + return flag; + } + + private static Instant instant(Object value) { + String text = text(value); + Instant instant = Instant.parse(text); + if (!instant.toString().equals(text)) throw invalid("Canonical timestamp required"); + return instant; + } + + private static void validateFacts(Map facts, Snapshot membership) { + String kind = text(facts.get("sourceKind")); + if (!Set.of("PAID_HOSTING", "NON_PAID_DEMO").contains(kind) + || facts.get("provisioningStatus") != null) + throw invalid("Current explicit source required"); + Object status = facts.get("subscriptionStatus"); + if ("NON_PAID_DEMO".equals(kind) + ? status != null + : !(status instanceof String) + || !Set.of("trialing", "active", "past_due", "grace", "suspended", "canceled") + .contains(status)) throw invalid("Source subscription status differs"); + for (String key : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) + if (!(facts.get(key) instanceof Boolean)) + throw invalid("Explicit entitlement booleans required"); + positive(facts.get("entitlementVersion")); + positive(facts.get("tenantBillingSequence")); + positive(facts.get("tenantAuthorityGeneration")); + var tuple = membership.authorityTuple(); + var cutoff = + tuple + .tenantBillingCutoff() + .orElseThrow(() -> invalid("Billing cutoff required")) + .get(membership.tenantId()); + if (!Objects.equals( + tuple.tenantAuthorityGeneration().get(membership.tenantId()), + facts.get("tenantAuthorityGeneration")) + || cutoff == null + || !Objects.equals(cutoff.tenantBillingSequence(), facts.get("tenantBillingSequence"))) + throw invalid("Facts differ from current tenant authority"); + if (!(facts.get("quotas") instanceof Map quotas) + || !quotas + .keySet() + .equals(Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"))) + throw invalid("Complete quotas required"); + quotas + .values() + .forEach( + value -> { + if (!text(value).matches("0|[1-9][0-9]{0,18}") || Long.parseLong(text(value)) < 0) + throw invalid("Nonnegative quota required"); + }); + } + + private static Map tuple(Snapshot membership) { + var supplied = membership.authorityTuple(); + Map result = new LinkedHashMap<>(); + result.put("issuerAuthGeneration", supplied.issuerAuthGeneration()); + result.put("accountAuthorityGeneration", supplied.accountAuthorityGeneration()); + result.put("tenantAuthorityGeneration", supplied.tenantAuthorityGeneration()); + result.put("membershipAuthorityGeneration", supplied.membershipAuthorityGeneration()); + result.put("privateRealmGrantVersions", supplied.privateRealmGrantVersions()); + supplied.accountSecurityCutoff().ifPresent(value -> result.put("accountSecurityCutoff", value)); + supplied.tenantBillingCutoff().ifPresent(value -> result.put("tenantBillingCutoff", value)); + return result; + } + + private static void exact(Map fields, Set expected) { + if (fields == null || !fields.keySet().equals(expected)) + throw invalid("Missing or extra scoped fields"); + } + + private static String text(Object value) { + if (!(value instanceof String text) || text.isBlank()) throw invalid("Required text absent"); + return text; + } + + private static void requireUuid(String value) { + if (!UUID.fromString(value).toString().equals(value) || new UUID(0, 0).toString().equals(value)) + throw invalid("Canonical UUID required"); + } + + private static void positive(Object value) { + if (!text(value).matches("[1-9][0-9]{0,18}") || Long.parseLong(text(value)) <= 0) + throw invalid("Positive owner counter required"); + } + + private static byte[] canonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException failure) { + throw invalid("Cannot encode canonical player evidence"); + } + } + + public static String digest(Map preimage) { + return digestBytes(canonical(preimage)); + } + + public static String digestBytes(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + public Instant evaluatedAt() { + return instant(fields().get("evaluatedAt")); + } + + public Instant validUntil() { + return instant(fields().get("validUntil")); + } + + /** Applies actual source time bounds only; this never establishes a current World hold. */ + public void requireCurrentAt(Instant now) { + Objects.requireNonNull(now); + if (now.isBefore(evaluatedAt()) || !now.isBefore(validUntil())) + throw invalid("Player entitlement source observation expired"); + } + + public Snapshot membershipSource() { + return membership; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** A detached copy; editing it cannot alter this value. */ + public Map fields() { + return JSON.readValue( + new String(canonicalBytes, StandardCharsets.UTF_8), new TypeReference<>() {}); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + @Override + public boolean equals(Object other) { + return other instanceof RuntimePlayerAdmissionEntitlementEvidence value + && Arrays.equals(canonicalBytes, value.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + @Override + public String toString() { + return "RuntimePlayerAdmissionEntitlementEvidence[PLAYER_ADMISSION, redacted]"; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java new file mode 100644 index 0000000000..32ca98404d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Controlled content fixtures, not source authentication, transport or owner execution. */ +class RuntimePlayerAdmissionEntitlementEvidenceTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String HASH = "a".repeat(64); + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + + @Test + void canonicalVariantRetainsExplicitAbsenceAndCompleteApplicableAuthority() { + var value = capture(target(), facts(), sources(), NOW); + assertThat(value.fields()) + .containsEntry("variant", "PLAYER_ADMISSION") + .containsEntry("authorityAvailability", "AVAILABLE") + .containsEntry("callerAccountId", ACCOUNT.toString()) + .containsEntry("verifiedConnectScopeId", "controlled-scope") + .containsEntry("membershipExists", false) + .containsEntry("membershipLifecycleState", "MISSING"); + assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(value.membershipSource().checkpoints()).hasSize(4); + assertThat(value.membershipSource().sourceEvidence()).hasSize(1); + byte[] copy = value.canonicalBytes(); + copy[0] = 0; + value.fields().put("callerAccountId", TENANT.toString()); + assertThat(value.fields()).containsEntry("callerAccountId", ACCOUNT.toString()); + assertThat(value.toString()).doesNotContain("controlled-scope"); + assertThatThrownBy( + () -> RuntimeTenantOperationEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void identitiesBindActualInputsAndSeparateSnapshotFromEvaluation() { + var first = capture(target(), facts(), sources(), NOW); + var later = capture(target(), facts(), sources(), NOW.plusSeconds(1)); + assertThat(first.fields().get("snapshotIdentity")) + .isEqualTo(later.fields().get("snapshotIdentity")); + assertThat(first.fields().get("evaluationIdentity")) + .isNotEqualTo(later.fields().get("evaluationIdentity")); + var changed = sources(); + changed.put("worldLifecycleDigest", "sha256:" + "b".repeat(64)); + assertThat(capture(target(), facts(), changed, NOW).fields().get("snapshotIdentity")) + .isNotEqualTo(first.fields().get("snapshotIdentity")); + } + + @Test + void incompleteOrConflictingTargetFactsAndSourcesNeverProduceAValue() { + for (String field : List.of("activeWorldEpoch", "canonicalVersionId", "targetClass")) { + var target = target(); + target.remove(field); + assertThatThrownBy(() -> capture(target, facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + for (String field : List.of("tenantAuthorityGeneration", "tenantBillingSequence")) { + var facts = facts(); + facts.put(field, "9"); + assertThatThrownBy(() -> capture(target(), facts, sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + var unframedScopeSource = sources(); + unframedScopeSource.put("scopeDigest", HASH); + assertThatThrownBy(() -> capture(target(), facts(), unframedScopeSource, NOW)) + .isInstanceOf(IllegalArgumentException.class); + var target = target(); + target.put("characterCreationPolicy", "PLAYER_CREATED"); + assertThatThrownBy(() -> capture(target, facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + var source = sources(); + source.put("callerGeneration", "1"); + assertThatThrownBy(() -> capture(target(), facts(), source, NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> capture(target(), facts(), sources(), NOW.plusSeconds(120))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void strictDecoderRoundTripsAndRejectsNoncanonicalUnknownOrConflictingContent() { + var value = capture(target(), facts(), sources(), NOW); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + String json = new String(value.canonicalBytes(), StandardCharsets.UTF_8); + for (byte[] malformed : + List.of( + (" " + json).getBytes(StandardCharsets.UTF_8), + json.replace("\"variant\":\"PLAYER_ADMISSION\"", "\"variant\":\"TENANT_OPERATION\"") + .getBytes(StandardCharsets.UTF_8), + (json.substring(0, json.length() - 1) + ",\"unknown\":true}") + .getBytes(StandardCharsets.UTF_8), + (json.substring(0, json.length() - 1) + ",\"variant\":\"PLAYER_ADMISSION\"}") + .getBytes(StandardCharsets.UTF_8), + json.replace("\"membershipExists\":false", "\"membershipExists\":true") + .getBytes(StandardCharsets.UTF_8), + json.replace("\"pointerVersion\":\"3\"", "\"pointerVersion\":\"4\"") + .getBytes(StandardCharsets.UTF_8), + new byte[] {(byte) 0xc3, (byte) 0x28}, + new byte[RuntimePlayerAdmissionEntitlementEvidence.MAX_CANONICAL_BYTES + 1])) { + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void validityIsMinimumOfActualScopeCallerAndPaidReceiptBounds() { + var source = sources(); + var demo = capture(target(), facts(), source, NOW); + assertThat(demo.validUntil()).isEqualTo(NOW.plusSeconds(90)); + demo.requireCurrentAt(NOW.plusSeconds(89)); + assertThatThrownBy(() -> demo.requireCurrentAt(NOW.plusSeconds(90))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> demo.requireCurrentAt(NOW.minusSeconds(1))) + .isInstanceOf(IllegalArgumentException.class); + var paid = facts(); + paid.put("sourceKind", "PAID_HOSTING"); + paid.put("subscriptionStatus", "active"); + source.put("paidReceiptValidUntil", NOW.plusSeconds(4).toString()); + var value = capture(target(), paid, source, NOW); + assertThat(value.validUntil()).isEqualTo(NOW.plusSeconds(4)); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + source.put("paidReceiptValidUntil", NOW.toString()); + assertThatThrownBy(() -> capture(target(), paid, source, NOW)) + .isInstanceOf(IllegalArgumentException.class); + source.put("paidReceiptValidUntil", null); + assertThatThrownBy(() -> capture(target(), paid, source, NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REQUEST.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", REQUEST.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", REQUEST.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + REQUEST, + REQUEST, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + REQUEST, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + TENANT.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + ACCOUNT.toString(), + TENANT.toString(), + false, + "MISSING", + false, + Map.of(TENANT.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + ACCOUNT, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java new file mode 100644 index 0000000000..4ef24c0535 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.common.account.authority; + +import com.google.protobuf.ByteString; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.account.v1.PlayerAdmissionEntitlementReadSelectors; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Closed comparison and content mapping; this codec authenticates neither callers nor sources. */ +public final class RuntimePlayerAdmissionEntitlementGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 40 * 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + RuntimePlayerAdmissionEntitlementEvidence.MAX_CANONICAL_BYTES + MAX_REQUEST_WIRE_BYTES + 32; + public static final long CALL_DEADLINE_SECONDS = 45L; + + private RuntimePlayerAdmissionEntitlementGrpcCodec() {} + + public record Request(RetainedTargetSelector target, String connectScopeId) { + public Request { + Objects.requireNonNull(target, "Exact retained target selectors required"); + if (connectScopeId == null + || connectScopeId.isBlank() + || connectScopeId.length() + > RuntimePlayerAdmissionEntitlementEvidence.MAX_CONNECT_SCOPE_CHARS) throw invalid(); + } + + public String expectedGameSessionWorkload() { + return "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"; + } + + @Override + public String toString() { + return "PlayerAdmissionEntitlementSelectors[redacted]"; + } + } + + /** Process-local credential carrier only; never include in logs or a persisted operation. */ + public record PresentedRequest(Request request, String initialLoginJwt) { + public PresentedRequest { + Objects.requireNonNull(request); + if (initialLoginJwt == null + || initialLoginJwt.isBlank() + || initialLoginJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || !initialLoginJwt.matches("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+")) + throw invalid(); + } + + @Override + public String toString() { + return "PlayerAdmissionEntitlementCredential[redacted]"; + } + } + + public static ReadPlayerAdmissionEntitlementRequest toRequest( + Request request, String initialLoginJwt) { + new PresentedRequest(request, initialLoginJwt); + var wire = + ReadPlayerAdmissionEntitlementRequest.newBuilder() + .addSelectors(selectors(request)) + .addInitialLoginJwt(initialLoginJwt) + .build(); + if (wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) throw invalid(); + return wire; + } + + public static PresentedRequest parseRequest(ReadPlayerAdmissionEntitlementRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + return new PresentedRequest( + parseSelectors(one(wire.getSelectorsList())), one(wire.getInitialLoginJwtList())); + } + + public static ReadPlayerAdmissionEntitlementResponse toResponse( + Request request, RuntimePlayerAdmissionEntitlementEvidence evidence) { + requireBinding(request, evidence); + var wire = + ReadPlayerAdmissionEntitlementResponse.newBuilder() + .addRequest(selectors(request)) + .addCanonicalEvidence(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + if (wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) throw invalid(); + return wire; + } + + public static RuntimePlayerAdmissionEntitlementEvidence requireResponse( + Request expected, ReadPlayerAdmissionEntitlementResponse wire) { + Objects.requireNonNull(expected); + if (wire == null + || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || !expected.equals(parseSelectors(one(wire.getRequestList())))) throw invalid(); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( + one(wire.getCanonicalEvidenceList()).toByteArray()); + requireBinding(expected, evidence); + return evidence; + } + + private static PlayerAdmissionEntitlementReadSelectors selectors(Request request) { + return PlayerAdmissionEntitlementReadSelectors.newBuilder() + .addSchemaVersion(1) + .addTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( + request.target())) + .addConnectScopeId(request.connectScopeId()) + .build(); + } + + private static Request parseSelectors(PlayerAdmissionEntitlementReadSelectors wire) { + if (wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || one(wire.getSchemaVersionList()) != 1) throw invalid(); + return new Request( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + one(wire.getTargetList())), + one(wire.getConnectScopeIdList())); + } + + private static void requireBinding( + Request request, RuntimePlayerAdmissionEntitlementEvidence evidence) { + Map fields = Objects.requireNonNull(evidence).fields(); + var target = request.target(); + if (!target.accountId().toString().equals(fields.get("callerAccountId")) + || !target.tenantId().toString().equals(fields.get("tenantId")) + || !target.readRequestId().toString().equals(fields.get("requestId")) + || !request.expectedGameSessionWorkload().equals(fields.get("callerWorkload")) + || !request.connectScopeId().equals(fields.get("verifiedConnectScopeId"))) throw invalid(); + if (!(fields.get("target") instanceof Map actual) + || !target.targetNamespace().equals(actual.get("targetNamespace")) + || !target.tenantId().toString().equals(actual.get("tenantId")) + || !target.tenantSlug().equals(actual.get("tenantSlug")) + || !target.worldSlug().equals(actual.get("worldSlug")) + || !target.realmId().toString().equals(actual.get("realmId")) + || !target.realmSlug().equals(actual.get("realmSlug")) + || !target + .playableStateNamespaceId() + .toString() + .equals(actual.get("playableStateNamespaceId")) + || !target.playableStateScope().equals(actual.get("playableStateScope")) + || !target.gameInstanceId().toString().equals(actual.get("gameInstanceId")) + || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) + || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion"))) + throw invalid(); + } + + private static T one(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Exact bounded player-admission entitlement evidence required"); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java new file mode 100644 index 0000000000..7d19d96322 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Controlled content and wire fixtures only; no source authentication or owner execution. */ +class RuntimePlayerAdmissionEntitlementGrpcCodecTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String HASH = "a".repeat(64); + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final String TOKEN = "controlled.initial.jwt"; + + private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( + UUID account, UUID requestId) { + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + new RetainedTargetSelector( + requestId, + account, + "prod", + TENANT, + "tenant", + "world", + REQUEST, + "production", + REQUEST, + "SHARED", + REQUEST, + 7, + 3), + "controlled-scope"); + } + + @Test + void exactRoundTripPreservesSelectorsAndNeverEchoesCredential() { + var request = request(ACCOUNT, REQUEST); + var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); + var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); + assertThat(presented.request()).isEqualTo(request); + assertThat(presented.initialLoginJwt()).isEqualTo(TOKEN); + assertThat(presented.toString()).doesNotContain(TOKEN, "controlled-scope"); + assertThat(request.toString()).doesNotContain("controlled-scope"); + var value = capture(target(), facts(), sources(), NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + assertThat(RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response)) + .isEqualTo(value); + assertThat(response.toByteString().toStringUtf8()).doesNotContain(TOKEN); + } + + @Test + void missingDuplicateUnknownAndOversizedMembersAreRejected() { + var request = request(ACCOUNT, REQUEST); + var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var malformed : + List.of( + wire.getDefaultInstanceForType(), + wire.toBuilder().addSelectors(wire.getSelectors(0)).build(), + wire.toBuilder().addInitialLoginJwt(TOKEN).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setSelectors(0, wire.getSelectors(0).toBuilder().addSchemaVersion(1)) + .build(), + wire.toBuilder() + .setSelectors(0, wire.getSelectors(0).toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder().setInitialLoginJwt(0, "a".repeat(45000)).build())) { + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + var response = + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( + request, capture(target(), facts(), sources(), NOW)); + for (var malformed : + List.of( + response.getDefaultInstanceForType(), + response.toBuilder().addRequest(response.getRequest(0)).build(), + response.toBuilder().addCanonicalEvidence(response.getCanonicalEvidence(0)).build(), + response.toBuilder().setUnknownFields(unknown).build(), + response.toBuilder() + .setCanonicalEvidence(0, com.google.protobuf.ByteString.copyFromUtf8("{}")) + .build())) { + assertThatThrownBy( + () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void changedCallerRequestOrScopeCannotBeReturnedAsCorrelatedEvidence() { + var request = request(ACCOUNT, REQUEST); + var value = capture(target(), facts(), sources(), NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + for (var other : + List.of( + request(UUID.randomUUID(), REQUEST), + request(ACCOUNT, UUID.randomUUID()), + new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + request.target(), "another-scope"))) { + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(other, value)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(other, response)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REQUEST.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", REQUEST.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", REQUEST.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + REQUEST, + REQUEST, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + REQUEST, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + TENANT.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + ACCOUNT.toString(), + TENANT.toString(), + false, + "MISSING", + false, + Map.of(TENANT.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + ACCOUNT, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index bf39db3a85..41d828031e 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -65,6 +65,7 @@ void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { assertField(descriptor, "membership_version", 6, FieldDescriptor.Type.UINT64); assertField(descriptor, "membership_authority_generation", 7, FieldDescriptor.Type.UINT64); + assertField(descriptor, "gameplay_admission_allowed", 10, FieldDescriptor.Type.BOOL); } @Test @@ -308,6 +309,49 @@ void directTextScopeIssuanceAndJoinRequireRegisteredAccountUuidAndKeepClockSnaps } } + @Test + void alreadyActiveNonAdmittingJoinReturnsMembershipReceiptWithoutGrantingAdmission() + throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + server.denyGameplayAdmission(); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var scopeRequest = validConnectScopeRequest(accountUuid); + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + String connectScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); + var before = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + var reply = + stub.joinPublicProductionMembership( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId(connectScopeId) + .setRequestId("join-request-1") + .build()); + + assertThat(reply.getSuccess()).isTrue(); + assertThat(reply.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(reply.getGameplayAdmissionAllowed()).isFalse(); + assertThat(reply.getMembershipVersion()).isEqualTo(before.getMembershipVersion()); + assertThat(reply.getMembershipAuthorityGeneration()) + .isEqualTo(before.getMembershipAuthorityGeneration()); + assertThat(reply.getMembershipId()).matches("[1-9][0-9]{0,18}"); + var after = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + assertThat(after.getMembershipExists()).isEqualTo(before.getMembershipExists()); + assertThat(after.getGameplayAdmissionAllowed()) + .isEqualTo(before.getGameplayAdmissionAllowed()); + assertThat(after.getMembershipVersion()).isEqualTo(before.getMembershipVersion()); + assertThat(after.getMembershipAuthorityGeneration()) + .isEqualTo(before.getMembershipAuthorityGeneration()); + } finally { + channel.shutdownNow(); + } + } + } + private static IssueDirectTextConnectScopeRequest validConnectScopeRequest(String accountUuid) { PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 7a132094fa..6f5fb07718 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -368,6 +368,18 @@ public void joinPublicProductionMembership( .setAccountId(caller.getAccountId()) .setTenantId(caller.getTenantId()) .build()); + } else if ("ACTIVE".equals(membershipLifecycleState.get())) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("ALREADY_ACTIVE") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId("1") + .setMembershipVersion(membershipVersion.get()) + .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) + .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) + .build()); } else { membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); @@ -377,10 +389,10 @@ public void joinPublicProductionMembership( .setOutcomeCode("JOINED") .setAccountId(caller.getAccountId()) .setTenantId(caller.getTenantId()) - .setMembershipId( - "stub-membership-" + caller.getAccountId() + "-" + caller.getTenantId()) - .setMembershipVersion(1L) - .setMembershipAuthorityGeneration(1L) + .setMembershipId("1") + .setMembershipVersion(membershipVersion.get()) + .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) + .setGameplayAdmissionAllowed(true) .build()); } responseObserver.onCompleted(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java new file mode 100644 index 0000000000..2d7373ca81 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; + +/** Exact same-row persisted discovery fields; zero is a legitimate stored level. */ +public record AccountBootstrapRosterActorProjection( + UUID characterUuid, String displayName, int level) { + public AccountBootstrapRosterActorProjection { + new CanonicalGameplayRosterActor(characterUuid, displayName); + if (level < 0) throw new IllegalArgumentException("Persisted actor level is invalid"); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java new file mode 100644 index 0000000000..94513fde0b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Purpose-specific certificate guard runs before protobuf decoding; no canonical GS allowlist + * change. + */ +public final class AccountBootstrapRosterPeerInterceptor implements ServerInterceptor { + public static final String METHOD_NAME = + "entity_management.v1.AccountBootstrapRosterReadService/ReadAccountBootstrapRoster"; + private static final Context.Key VERIFIED_ACCOUNT = + Context.key("firemud-account-bootstrap-roster-peer"); + private final String namespace; + + public AccountBootstrapRosterPeerInterceptor(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (!METHOD_NAME.equals(call.getMethodDescriptor().getFullMethodName())) { + return next.startCall(call, headers); + } + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .orElse(null); + if (peer == null) { + call.close( + Status.UNAUTHENTICATED.withDescription("Authenticated Account workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + if (!trusted(peer, namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + call.close( + Status.PERMISSION_DENIED.withDescription("Exact Account workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return Contexts.interceptCall( + Context.current() + .withValue(VERIFIED_ACCOUNT, peer) + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer), + call, + headers, + next); + } + + static boolean trusted(GrpcPeerIdentity peer, String namespace) { + return peer != null && peer.isService("account-service") && peer.isInNamespace(namespace); + } + + static GrpcPeerIdentity currentVerifiedPeer() { + return VERIFIED_ACCOUNT.get(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java new file mode 100644 index 0000000000..ff9f783dfa --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.util.HashSet; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.validation.CanonicalEntitySourceValues; + +/** Closed, bounded transient discovery contract. No original-selection or retention identities. */ +public final class AccountBootstrapRosterReadContract { + public static final int MAX_REQUEST_BYTES = 4096; + public static final int MAX_RESPONSE_BYTES = 64 * 1024; + public static final int MAX_ACTORS = 100; + + private AccountBootstrapRosterReadContract() {} + + public static CanonicalGameplayRosterTarget requireRequest( + AccountBootstrapRosterReadRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || !wire.hasExpectedTarget() + || !wire.getExpectedTarget().getUnknownFields().asMap().isEmpty() + || !GrpcPeerIdentity.isValidNamespace(wire.getTargetNamespace())) { + throw new IllegalArgumentException("Complete closed bootstrap roster request required"); + } + uuid(wire.getRequestUuid()); + uuid(wire.getCanonicalAccountUuid()); + var target = wire.getExpectedTarget(); + uuid(target.getTenantUuid()); + uuid(target.getRealmUuid()); + uuid(target.getGameInstanceUuid()); + uuid(target.getCanonicalVersionUuid()); + uuid(target.getPlayableStateNamespaceUuid()); + var parsed = CanonicalGameplayRosterTarget.fromWire(target); + if (!parsed.toWire().equals(target)) { + throw new IllegalArgumentException("Canonical exact target required"); + } + return parsed; + } + + public static AccountBootstrapRosterReadResponse requireResponse( + AccountBootstrapRosterReadRequest request, AccountBootstrapRosterReadResponse response) { + requireRequest(request); + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !request.equals(response.getRequest()) + || response.getActorsCount() > MAX_ACTORS) { + throw new IllegalArgumentException("Bounded exact bootstrap roster response required"); + } + String previous = null; + var seen = new HashSet(); + for (var actor : response.getActorsList()) { + if (!actor.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed actor projection required"); + } + UUID actorUuid = uuid(actor.getCharacterUuid()); + new CanonicalGameplayRosterActor(actorUuid, actor.getDisplayName()); + if (!actor.hasLevel() || actor.getLevel() < 0) { + throw new IllegalArgumentException("Actual persisted actor level required"); + } + if (!seen.add(actorUuid) + || (previous != null && previous.compareTo(actor.getCharacterUuid()) >= 0)) { + throw new IllegalArgumentException("Unique UUID-ordered actor projection required"); + } + previous = actor.getCharacterUuid(); + } + return response; + } + + public static UUID uuid(String value) { + return CanonicalEntitySourceValues.parseCanonicalNonNilUuid(value); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java new file mode 100644 index 0000000000..0a2d385803 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; + +/** Unregistered receiver. Install its dedicated peer interceptor in every manual composition. */ +public final class AccountBootstrapRosterReadGrpcService + extends AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceImplBase { + private final AccountBootstrapRosterReadService service; + private final String namespace; + + public AccountBootstrapRosterReadGrpcService( + AccountBootstrapRosterReadService service, String namespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void readAccountBootstrapRoster( + AccountBootstrapRosterReadRequest request, + StreamObserver observer) { + var peer = AccountBootstrapRosterPeerInterceptor.currentVerifiedPeer(); + if (peer == null) { + refuse(observer, Status.UNAUTHENTICATED); + return; + } + if (!AccountBootstrapRosterPeerInterceptor.trusted(peer, namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + refuse(observer, Status.PERMISSION_DENIED); + return; + } + AccountBootstrapRosterReadResponse response; + try { + AccountBootstrapRosterReadService.requireNoAmbientTransaction(); + AccountBootstrapRosterReadContract.requireRequest(request); + if (!namespace.equals(request.getTargetNamespace())) { + refuse(observer, Status.PERMISSION_DENIED); + return; + } + response = service.read(request); + } catch (OwnerEvidenceUnavailableException + | org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.CannotCreateTransactionException unavailable) { + refuse(observer, Status.UNAVAILABLE); + return; + } catch (UnsupportedOperationException | IllegalStateException precondition) { + refuse(observer, Status.FAILED_PRECONDITION); + return; + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unexpected) { + refuse(observer, Status.INTERNAL); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void refuse(StreamObserver observer, Status status) { + observer.onError( + status.withDescription("Account bootstrap roster read refused").asRuntimeException()); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java new file mode 100644 index 0000000000..a4e104cfcc --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Manually composed and unregistered Account discovery; no actor or receipt writes. */ +public final class AccountBootstrapRosterReadService { + private final GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter owner; + private final CharacterRepository characters; + private final TransactionTemplate reads; + + public AccountBootstrapRosterReadService( + GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter owner, + CharacterRepository characters, + PlatformTransactionManager transactionManager) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.characters = Objects.requireNonNull(characters, "characters"); + reads = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + reads.setReadOnly(true); + reads.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + reads.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + reads.setTimeout(5); + } + + public AccountBootstrapRosterReadResponse read(AccountBootstrapRosterReadRequest request) { + requireNoAmbientTransaction(); + CanonicalGameplayRosterTarget target = + AccountBootstrapRosterReadContract.requireRequest(request); + if (target.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { + throw new UnsupportedOperationException("Unsupported bootstrap roster target"); + } + requireCurrent(request, target); + var actors = + Objects.requireNonNull( + reads.execute( + ignored -> + characters.readAccountBootstrapRoster( + AccountBootstrapRosterReadContract.uuid(request.getCanonicalAccountUuid()), + target))); + // Source RPCs run outside SQL. This detects source movement over the local projection; + // it does not claim a distributed hold or protect a later admission/selection. + requireCurrent(request, target); + var response = AccountBootstrapRosterReadResponse.newBuilder().setRequest(request); + for (var actor : actors) { + response.addActors( + AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid(actor.characterUuid().toString()) + .setDisplayName(actor.displayName()) + .setLevel(actor.level())); + } + return AccountBootstrapRosterReadContract.requireResponse(request, response.build()); + } + + private void requireCurrent( + AccountBootstrapRosterReadRequest request, CanonicalGameplayRosterTarget target) { + requireNoAmbientTransaction(); + var current = + owner.resolveCurrentTarget( + AccountBootstrapRosterReadContract.uuid(request.getRequestUuid()), + AccountBootstrapRosterReadContract.uuid(request.getCanonicalAccountUuid()), + target); + if (current == null + || !current.requestUuid().toString().equals(request.getRequestUuid()) + || !current.canonicalAccountUuid().toString().equals(request.getCanonicalAccountUuid()) + || !target.equals(current.target())) { + throw new TargetChangedException(); + } + } + + public static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new TargetChangedException(); + } + } + + public static final class TargetChangedException extends IllegalStateException { + public TargetChangedException() { + super("Bootstrap roster target precondition failed"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 8d34f302f3..72feec9c3b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -1217,26 +1217,64 @@ private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) } } + /** + * Transient Account discovery only: reads existing canonical actor rows without enrolling a + * namespace, capturing a snapshot or creating an original-selection/retention receipt. The caller + * supplies a short owner read transaction after independently resolving current sources. + */ + public List< + net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection> + readAccountBootstrapRoster(UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(target, "target"); + if (!org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) { + throw new IllegalStateException("Account bootstrap discovery requires owner transaction"); + } + if (target.playableStateScope() + != net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED + || target.entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new UnsupportedOperationException("Account bootstrap target is unsupported"); + } + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(target.tenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + target.playableStateNamespaceId()))) + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + // A namespace with no rows may legitimately have no enrollment yet. Absence does not create + // enrollment or authority; the complete independently current owner target supplies scope. + if (enrolledScope != null && !target.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); + } + var rows = + canonicalRosterQuery(canonicalAccountUuid, target) + .fetch( + row -> + new net.firedevops.firemud.entitymanagement.bootstrap + .AccountBootstrapRosterActorProjection( + row.get(CHARACTERS.CHARACTER_UUID), + row.get(CHARACTERS.NAME), + row.get(CHARACTERS.LEVEL))); + if (rows.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); + } + return rows; + } + private List readCurrentCanonicalRoster( UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + var query = canonicalRosterQuery(canonicalAccountUuid, target); List actors = - dsl.select(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME) - .from(CHARACTERS) - .where( - CHARACTERS - .ACCOUNT_UUID - .eq(canonicalAccountUuid) - .and(CHARACTERS.TENANT_UUID.eq(target.tenantUuid())) - .and( - CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq( - target.playableStateNamespaceId())) - .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(target.playableStateScope().name())) - .and( - CHARACTERS.ACTOR_IDENTITY_STATUS.eq( - ActorIdentityStatus.OWNER_RESOLVED.name())) - .and(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON.isNull())) - .orderBy(CHARACTERS.CHARACTER_UUID.asc()) - .limit(CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE + 1) + query .forShare() .fetch( row -> @@ -1248,6 +1286,23 @@ private List readCurrentCanonicalRoster( return actors; } + private org.jooq.SelectLimitPercentStep> + canonicalRosterQuery(UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + return dsl.select(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME, CHARACTERS.LEVEL) + .from(CHARACTERS) + .where( + CHARACTERS + .ACCOUNT_UUID + .eq(canonicalAccountUuid) + .and(CHARACTERS.TENANT_UUID.eq(target.tenantUuid())) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(target.playableStateNamespaceId())) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(target.playableStateScope().name())) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.OWNER_RESOLVED.name())) + .and(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON.isNull())) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .limit(CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE + 1); + } + private CanonicalGameplayRosterSnapshot readBackCanonicalGameplayRosterSnapshot( UUID canonicalAccountUuid, CanonicalGameplayRosterTarget expectedTarget, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java index 6f2889e011..422512e04d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java @@ -60,7 +60,18 @@ public GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( CanonicalGameplayRosterReadRequest request) { Objects.requireNonNull(request, "request"); - CanonicalGameplayRosterTarget expected = request.expectedTarget(); + return resolveCurrentTarget( + request.requestUuid(), request.canonicalAccountUuid(), request.expectedTarget()); + } + + /** Non-admitting current source read, without inventing an original selection or session. */ + public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( + java.util.UUID requestUuid, + java.util.UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expected) { + Objects.requireNonNull(requestUuid, "requestUuid"); + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(expected, "expected"); if (expected.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED || expected.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { throw new UnsupportedOperationException( @@ -69,8 +80,8 @@ public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest = new CanonicalGameplayRosterOwnerReadEvidence.Request( - request.requestUuid(), - request.canonicalAccountUuid(), + requestUuid, + canonicalAccountUuid, workloadNamespace, expected.tenantUuid(), expected.worldSlug(), @@ -95,7 +106,7 @@ public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( } try { - return mapCompleteEvidence(request, ownerReadRequest, evidence); + return mapCompleteEvidence(ownerReadRequest, evidence); } catch (RuntimeException invalid) { if (invalid instanceof OwnerEvidenceUnavailableException unavailable) { throw unavailable; @@ -105,11 +116,9 @@ public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( } private CanonicalGameplayRosterOwnerEvidence mapCompleteEvidence( - CanonicalGameplayRosterReadRequest request, CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest, CanonicalGameplayRosterOwnerReadEvidence evidence) { - if (!request.requestUuid().equals(evidence.request().requestUuid()) - || !request.canonicalAccountUuid().equals(evidence.request().canonicalAccountUuid())) { + if (!ownerReadRequest.equals(evidence.request())) { throw new IllegalArgumentException("Game Session evidence changed request/account binding"); } GameSessionCanonicalInitialAdmissionOwnerProof proof = evidence.gameSessionOwnerProof(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java new file mode 100644 index 0000000000..02b847b8b9 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java @@ -0,0 +1,488 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual Entity/Saga migrations, assignment writer, read-only repository and two socket mTLS hops. + * Upstream COMMITTED target/published-policy bytes and assignment eligibility are controlled input; + * this does not execute Game Session/World/publication owner stores or prove production custody. + */ +@Testcontainers +@Timeout(value = 3, unit = TimeUnit.MINUTES) +@SuppressWarnings("resource") +class AccountBootstrapRosterPostgresMtlsIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Account bootstrap roster test CA", + new IdentitySpec( + "entity-server", "spiffe://firemud/ns/test/sa/entity-management-service", true), + new IdentitySpec("gs-server", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "entity-client", "spiffe://firemud/ns/test/sa/entity-management-service", false), + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", false), + new IdentitySpec( + "foreign-account", "spiffe://firemud/ns/other/sa/account-service", false), + new IdentitySpec( + "gs-client", "spiffe://firemud/ns/test/sa/game-session-service", false)); + } + + @Test + void persistedZeroOneAndAccountNamespaceIsolationHaveNoDiscoveryWrites() throws Exception { + try (var f = fixture()) { + var request = f.source.request(); + var before = f.rows(); + assertThat(f.read("account", request).getActorsList()).isEmpty(); + assertThat(f.rows()).isEqualTo(before); // valid empty does not enroll the namespace + UUID account = UUID.fromString(request.getCanonicalAccountUuid()); + UUID first = f.assign(account, f.source.target(), 101L, "Persisted Ship"); + f.dsl.execute("UPDATE characters SET level=7 WHERE character_uuid=?", first); + var one = f.read("account", request); + assertThat(one.getRequest()).isEqualTo(request); + assertThat(one.getActorsCount()).isEqualTo(1); + assertThat(one.getActors(0).getCharacterUuid()).isEqualTo(first.toString()); + assertThat(one.getActors(0).getDisplayName()).isEqualTo("Persisted Ship"); + assertThat(one.getActors(0).hasLevel()).isTrue(); + assertThat(one.getActors(0).getLevel()).isEqualTo(7); + // The current assignment writer/partial unique index permits one OWNER_RESOLVED actor per + // account namespace. This read does not widen that writer invariant to fabricate a many + // fixture. + UUID otherAccount = UUID.randomUUID(); + UUID zeroLevelActor = f.assign(otherAccount, f.source.target(), 102L, "Other Account"); + var otherNamespace = + request.getExpectedTarget().toBuilder() + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString()) + .build(); + f.assign( + account, CanonicalGameplayRosterTarget.fromWire(otherNamespace), 101L, "Other Namespace"); + f.dsl.execute( + "INSERT INTO characters (account_id,account_uuid,name,tenant_id,playable_state_key) VALUES (101,?,'Quarantined',1,'shared-live')", + account); + before = f.rows(); + var isolated = f.read("account", request); + assertThat(isolated.getActorsList().stream().map(actor -> actor.getCharacterUuid()).toList()) + .containsExactly(first.toString()); + assertThat(isolated.getActors(0).getLevel()).isEqualTo(7); + var storedZero = + f.read( + "account", + request.toBuilder().setCanonicalAccountUuid(otherAccount.toString()).build()); + assertThat(storedZero.getActors(0).getCharacterUuid()).isEqualTo(zeroLevelActor.toString()); + assertThat(storedZero.getActors(0).hasLevel()).isTrue(); + assertThat(storedZero.getActors(0).getLevel()).isZero(); + assertThat( + f.read( + "account", + request.toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString()) + .build()) + .getActorsList()) + .isEmpty(); + assertThat(f.rows()).isEqualTo(before); + assertThat(f.ownerReads.get()).isEqualTo(10); + } + } + + @Test + void workloadGuardPrecedesMalformedDecodeAndUnsupportedScopeOrNamespaceNeverQueriesSource() + throws Exception { + try (var f = fixture()) { + var malformed = + f.source.request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + f.refuses("foreign-account", malformed, Status.Code.PERMISSION_DENIED); + f.refuses("gs-client", malformed, Status.Code.PERMISSION_DENIED); + f.refuses("account", malformed, Status.Code.INVALID_ARGUMENT); + f.refuses( + "account", + f.source.request().toBuilder().setTargetNamespace("other").build(), + Status.Code.PERMISSION_DENIED); + f.refuses( + "account", + f.source.request().toBuilder() + .setExpectedTarget( + f.source.request().getExpectedTarget().toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .build(), + Status.Code.FAILED_PRECONDITION); + f.refuses( + "account", + f.source.request().toBuilder() + .setExpectedTarget( + f.source.request().getExpectedTarget().toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED)) + .build(), + Status.Code.FAILED_PRECONDITION); + assertThat(f.ownerReads.get()).isZero(); + } + } + + @Test + void unavailableChangedDigestAndSourceMovementAcrossSqlRefuseWithoutEmptySuccess() + throws Exception { + try (var f = fixture()) { + var before = f.rows(); + f.unavailable = true; + f.refuses("account", f.source.request(), Status.Code.UNAVAILABLE); + f.unavailable = false; + f.pointerDigest.set("f".repeat(64)); + f.refuses("account", f.source.request(), Status.Code.FAILED_PRECONDITION); + f.pointerDigest.set(f.source.target().admissionPointerSnapshotDigest()); + f.changeAfterNextSourceRead = true; + f.refuses("account", f.source.request(), Status.Code.FAILED_PRECONDITION); + assertThat(f.rows()).isEqualTo(before); + } + } + + private static Fixture fixture() throws Exception { + String schema = "entity_bootstrap_" + UUID.randomUUID().toString().replace("-", ""); + var ds = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + ds.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(ds) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_entity_management_service") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", schema)); + migration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + migration.load().migrate(); + return new Fixture( + schema, + DSL.using(new TransactionAwareDataSourceProxy(ds), SQLDialect.POSTGRES), + new DataSourceTransactionManager(ds)); + } + + private static final class Fixture implements AutoCloseable { + final String schema; + final DSLContext dsl; + final DataSourceTransactionManager manager; + final CharacterRepository characters; + final AccountBootstrapRosterFixture.Fixture source; + final AtomicInteger ownerReads = new AtomicInteger(); + final AtomicReference pointerDigest; + volatile boolean unavailable; + volatile boolean changeAfterNextSourceRead; + final Server sourceServer; + final Server entityServer; + final GameSessionCanonicalGameplayRosterOwnerReadClient client; + final List channels = new ArrayList<>(); + + Fixture(String schema, DSLContext dsl, DataSourceTransactionManager manager) throws Exception { + this.schema = schema; + this.dsl = dsl; + this.manager = manager; + characters = new CharacterRepository(dsl); + source = AccountBootstrapRosterFixture.create(); + pointerDigest = new AtomicReference<>(source.target().admissionPointerSnapshotDigest()); + sourceServer = + server( + "gs-server", + new CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase() { + @Override + public void getCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace("test")) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + ownerReads.incrementAndGet(); + if (unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + var request = CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(wire); + var base = source.evidence().request(); + var rebound = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + base.targetNamespace(), + base.canonicalTenantUuid(), + base.worldSlug(), + base.realmUuid(), + base.realmSlug(), + base.playableStateNamespaceUuid(), + base.playableStateScope(), + base.canonicalGameInstanceUuid(), + base.canonicalVersionUuid(), + base.expectedCatalogRevision(), + base.expectedPointerVersion(), + base.expectedActiveWorldEpoch()); + if (!request.equals(rebound)) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + var evidence = + new CanonicalGameplayRosterOwnerReadEvidence( + request, + pointerDigest.get(), + source.evidence().gameSessionOwnerProof(), + source.evidence().publishedPolicySetEvidence()); + if (changeAfterNextSourceRead) { + pointerDigest.set("f".repeat(64)); + changeAfterNextSourceRead = false; + } + observer.onNext( + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request, evidence)); + observer.onCompleted(); + } + }, + new GrpcPeerIdentityInterceptor()); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + sourceServer.getPort()); + client = + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("entity-client")), + new GrpcChannelFactory(), + "test"); + client.init(); + var service = + new AccountBootstrapRosterReadService( + new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, "test"), + characters, + manager); + entityServer = + server( + "entity-server", + new AccountBootstrapRosterReadGrpcService(service, "test"), + new AccountBootstrapRosterPeerInterceptor("test")); + } + + AccountBootstrapRosterReadResponse read(String alias, AccountBootstrapRosterReadRequest request) + throws Exception { + var identity = pki.identity(alias); + var channel = + NettyChannelBuilder.forAddress("127.0.0.1", entityServer.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager( + identity.privateKey(), identity.certificate(), pki.caCertificate()) + .build()) + .intercept( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/test/sa/entity-management-service")) + .maxInboundMessageSize(AccountBootstrapRosterReadContract.MAX_RESPONSE_BYTES) + .build(); + channels.add(channel); + return AccountBootstrapRosterReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readAccountBootstrapRoster(request); + } + + void refuses(String alias, AccountBootstrapRosterReadRequest request, Status.Code expected) { + assertThatThrownBy(() -> read(alias, request)) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + UUID assign(UUID account, CanonicalGameplayRosterTarget target, long rowId, String name) { + UUID operation = UUID.randomUUID(); + var evidence = + new PreseededActorAssignmentOwnerEvidence( + operation, + account, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 4L, + "1".repeat(64), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef()); + var request = + new PreseededActorAssignmentRequest( + operation, + account, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, name), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + var result = + new TransactionTemplate(manager) + .execute( + ignored -> + characters.assignPreseededActor( + request, + evidence, + new RuntimeAccountIdentityEvidence( + 1, "test", operation, account, rowId, "ACCOUNT_DATABASE_INSERT"), + request.mutationIntentDigest())); + assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + return result.characterUuid(); + } + + Map> rows() { + var rows = new LinkedHashMap>(); + for (String table : + List.of( + "characters", + "entity_playable_state_namespace_scopes", + "entity_preseeded_actor_assignment_operations", + "entity_canonical_gameplay_roster_snapshots", + "entity_canonical_gameplay_roster_snapshot_actors", + "entity_canonical_roster_original_selections", + "entity_canonical_roster_admissions", + "entity_canonical_roster_retention_references")) { + rows.put( + table, + dsl.fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class)); + } + return rows; + } + + @Override + public void close() throws Exception { + for (var channel : channels) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + entityServer.shutdownNow(); + assertThat(entityServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + client.close(); + sourceServer.shutdownNow(); + assertThat(sourceServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static Server server( + String alias, io.grpc.BindableService service, io.grpc.ServerInterceptor interceptor) + throws Exception { + var identity = pki.identity(alias); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .maxInboundMessageSize(AccountBootstrapRosterReadContract.MAX_REQUEST_BYTES) + .addService(ServerInterceptors.intercept(service, interceptor)) + .build() + .start(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java new file mode 100644 index 0000000000..deac9277d9 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java @@ -0,0 +1,108 @@ +package unit.net.firedevops.firemud.entitymanagement.bootstrap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.*; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterPeerInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AccountBootstrapRosterPeerInterceptorTest { + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void exactAccountCertificateIsAvailableBeforeMessageHandling() throws Exception { + var call = call("spiffe://firemud/ns/test/sa/account-service"); + ServerCallHandler next = mock(ServerCallHandler.class); + when(next.startCall(any(), any())) + .thenAnswer( + ignored -> { + assertThat(GrpcPeerIdentity.current().isService("account-service")).isTrue(); + assertThat(GrpcPeerIdentity.current().isInNamespace("test")).isTrue(); + return new ServerCall.Listener() {}; + }); + new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); + verify(next).startCall(any(), any()); + } + + @Test + void absentWrongNamespaceAndGameSessionPeersNeverStartMessageDecoding() throws Exception { + for (String identity : + new String[] { + null, + "spiffe://firemud/ns/other/sa/account-service", + "spiffe://firemud/ns/test/sa/game-session-service" + }) { + var call = call(identity); + ServerCallHandler next = mock(ServerCallHandler.class); + new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); + verify(next, never()).startCall(any(), any()); + verify(call) + .close( + argThat( + status -> + status.getCode() + == (identity == null + ? Status.Code.UNAUTHENTICATED + : Status.Code.PERMISSION_DENIED)), + any()); + } + } + + @Test + void callerRoleAndInternalServiceContextsCannotSupplyDiscoveryAuthority() throws Exception { + for (boolean internal : List.of(false, true)) { + SessionContext.setContext( + internal ? null : "11111111-1111-4111-8111-111111111111", + internal ? List.of() : List.of("platformAdmin"), + Map.of(), + internal, + "account-service", + "instance"); + var call = call("spiffe://firemud/ns/test/sa/account-service"); + ServerCallHandler next = mock(ServerCallHandler.class); + new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); + verify(next, never()).startCall(any(), any()); + verify(call) + .close(argThat(status -> status.getCode() == Status.Code.PERMISSION_DENIED), any()); + SessionContext.clear(); + } + } + + private static ServerCall call(String identity) throws Exception { + ServerCall call = mock(ServerCall.class); + MethodDescriptor descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()) + .thenReturn(AccountBootstrapRosterPeerInterceptor.METHOD_NAME); + when(call.getMethodDescriptor()).thenReturn(descriptor); + var attributes = Attributes.EMPTY; + if (identity != null) { + X509Certificate leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, identity))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + attributes = Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + } + when(call.getAttributes()).thenReturn(attributes); + return call; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java new file mode 100644 index 0000000000..2b46dfa4b1 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -0,0 +1,219 @@ +package unit.net.firedevops.firemud.entitymanagement.bootstrap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadContract; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadService; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountBootstrapRosterReadServiceTest { + @Test + void realAdapterReadsCurrentSourceBeforeAndAfterShortLocalProjectionIncludingEmpty() + throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + when(client.getCanonicalGameplayRosterOwnerRead(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat( + invocation.getArgument( + 0, CanonicalGameplayRosterOwnerReadEvidence.Request.class)) + .isEqualTo(f.evidence().request()); + return f.evidence(); + }); + UUID actor = UUID.randomUUID(); + when(repository.readAccountBootstrapRoster(any(), eq(f.target()))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + return List.of( + new AccountBootstrapRosterActorProjection(actor, "Persisted Actor", 7)); + }) + .thenReturn(List.of()); + var service = service(client, repository); + assertThat(service.read(f.request()).getActorsList()) + .containsExactly( + AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid(actor.toString()) + .setDisplayName("Persisted Actor") + .setLevel(7) + .build()); + assertThat(service.read(f.request()).getActorsList()).isEmpty(); + verify(client, times(4)).getCanonicalGameplayRosterOwnerRead(f.evidence().request()); + verify(repository, times(2)) + .readAccountBootstrapRoster( + UUID.fromString(f.request().getCanonicalAccountUuid()), f.target()); + verifyNoMoreInteractions(client, repository); + } + + @Test + void sourceChangedBeforeSqlOrDuringProjectionNeverReturnsEmptySuccess() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var changed = + new CanonicalGameplayRosterOwnerReadEvidence( + f.evidence().request(), + "f".repeat(64), + f.evidence().gameSessionOwnerProof(), + f.evidence().publishedPolicySetEvidence()); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(changed); + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + verifyNoInteractions(repository); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(f.evidence(), changed); + when(repository.readAccountBootstrapRoster(any(), any())).thenReturn(List.of()); + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + verify(repository).readAccountBootstrapRoster(any(), any()); + } + + @Test + void unavailableOrWrongAccountSourceCannotBeAnEmptyRoster() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + when(client.getCanonicalGameplayRosterOwnerRead(any())) + .thenThrow(new IllegalStateException("offline")); + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(OwnerEvidenceUnavailableException.class); + org.mockito.Mockito.doReturn(f.evidence()) + .when(client) + .getCanonicalGameplayRosterOwnerRead(any()); + var changedAccount = + f.request().toBuilder().setCanonicalAccountUuid(UUID.randomUUID().toString()).build(); + assertThatThrownBy(() -> service.read(changedAccount)) + .isInstanceOf(OwnerEvidenceUnavailableException.class); + verifyNoInteractions(repository); + } + + @Test + void malformedUnsupportedAndAmbientTransactionRefuseBeforeAnySourceOrSql() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + assertThatThrownBy( + () -> service.read(f.request().toBuilder().setCanonicalAccountUuid("12").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.read( + f.request().toBuilder() + .setExpectedTarget( + f.request().getExpectedTarget().toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .build())) + .isInstanceOf(UnsupportedOperationException.class); + var unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> service.read(f.request().toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + new TransactionTemplate(new LocalTransactions()) + .executeWithoutResult( + ignored -> { + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + }); + verifyNoInteractions(client, repository); + } + + @Test + void exactEchoClosedActorBoundsCanonicalIdsAndDeterministicOrderAreRequired() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var first = + AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid("11111111-1111-4111-8111-111111111111") + .setDisplayName("First") + .setLevel(0) + .build(); + var second = first.toBuilder().setCharacterUuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").build(); + var valid = + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(f.request()) + .addActors(first) + .addActors(second) + .build(); + assertThat(AccountBootstrapRosterReadContract.requireResponse(f.request(), valid)) + .isEqualTo(valid); + for (var invalid : + List.of( + valid.toBuilder() + .setRequest(f.request().toBuilder().setRequestUuid(UUID.randomUUID().toString())) + .build(), + valid.toBuilder().addActors(second).build(), + valid.toBuilder().clearActors().addActors(second).addActors(first).build(), + valid.toBuilder() + .clearActors() + .addActors(first.toBuilder().setCharacterUuid("1")) + .build(), + valid.toBuilder() + .clearActors() + .addActors(first.toBuilder().setDisplayName(" First")) + .build(), + valid.toBuilder().clearActors().addActors(first.toBuilder().clearLevel()).build(), + valid.toBuilder().clearActors().addActors(first.toBuilder().setLevel(-1)).build(), + valid.toBuilder().addAllActors(java.util.Collections.nCopies(100, second)).build())) { + assertThatThrownBy( + () -> AccountBootstrapRosterReadContract.requireResponse(f.request(), invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static AccountBootstrapRosterReadService service( + GameSessionCanonicalGameplayRosterOwnerReadClient client, CharacterRepository repository) { + return new AccountBootstrapRosterReadService( + new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( + client, AccountBootstrapRosterFixture.NAMESPACE), + repository, + new LocalTransactions()); + } + + private static final class LocalTransactions extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object tx, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java new file mode 100644 index 0000000000..20081e085b --- /dev/null +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.testing.PlayerCreatedPublishedPolicyFixtures; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import tools.jackson.databind.json.JsonMapper; + +/** + * Complete closed upstream bytes are controlled test input, not executed publication/World custody. + */ +public final class AccountBootstrapRosterFixture { + public static final String NAMESPACE = "test"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AccountBootstrapRosterFixture() {} + + public record Fixture( + AccountBootstrapRosterReadRequest request, + CanonicalGameplayRosterTarget target, + CanonicalGameplayRosterOwnerReadEvidence evidence) {} + + public static Fixture create() throws Exception { + var account = AuthoringFixtures.freshGraphRequest().accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var prepared = PlayerCreatedPublishedPolicyFixtures.prepare(draft); + var operation = + new GameDesignPublicationOperationBinding( + prepared.account(), + prepared.world(), + IsolatedWorldPublicationInventoryFixtures.stipulated( + prepared.account(), prepared.world())); + var world = prepared.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(draft.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? world.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? "sha256:" + "a".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + world.canonicalTenantId(), + world.canonicalVersionId(), + "bundle:bootstrap-test", + 3, + "v2", + world.publishWorkflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of("LOOK"), + "generation-1", + prepared.world()); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + 6L); + var policy = + RealmEntryPolicy.parse( + """ + {"schemaVersion":1,"worldSlug":"earth","worldDisplayName":"Earth", + "realmSlug":"main","realmDisplayName":"Main","visible":true, + "publicProduction":true,"stateScope":"SHARED","entryPolicy":"PRESEEDED_ONLY"} + """, + JSON); + UUID policyId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + String logical = "realm-policy/earth/main"; + var selected = + new PublishedRealmEntryPolicyEvidence( + policyId, + draft.commitId(), + revisionId, + logical, + policy, + PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + draft.target(), + 3, + release.publishedReleaseBundleRef(), + release.contentDigest(), + world.publishWorkflowId(), + release.manifestHash(), + draft.commitId(), + revisionId, + logical, + policy)); + var snapshot = + Map.of( + "schema", + PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA, + "bindingJson", + draft.canonicalJson(), + "bindingDigest", + draft.digest(), + "sourceEpoch", + "1", + "policies", + List.of( + Map.of( + "commitId", + draft.commitId().toString(), + "revisionId", + revisionId.toString(), + "logicalRevisionId", + logical, + "policy", + JSON.readTree(policy.canonicalJson())))); + var capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + capture, Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot))); + var policies = List.of(selected); + String digest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + draft.target(), + 3, + draft.commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + world.publishWorkflowId(), + release.manifestHash(), + 6L, + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + policies); + var policySet = + new PublishedRealmEntryPolicySetEvidence( + draft.target(), + 3, + draft.commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + world.publishWorkflowId(), + release.manifestHash(), + 6L, + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + 1, + digest, + policies); + UUID realm = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + draft.target().canonicalTenantId(), + "earth", + realm, + namespace, + "SHARED", + instance, + draft.target().canonicalVersionId(), + 82L, + "controlled-initial-target", + "d".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null), + UUID.randomUUID(), + UUID.randomUUID()); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + var target = + new CanonicalGameplayRosterTarget( + draft.target().canonicalTenantId(), + realm, + "earth", + "main", + instance, + 71L, + 73L, + 82L, + draft.target().canonicalVersionId(), + selected.policyDigest().substring(7), + release.publishedReleaseBundleRef(), + "a".repeat(64), + "b".repeat(64), + namespace, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + var request = + AccountBootstrapRosterReadRequest.newBuilder() + .setRequestUuid(UUID.randomUUID().toString()) + .setCanonicalAccountUuid(UUID.randomUUID().toString()) + .setTargetNamespace(NAMESPACE) + .setExpectedTarget(target.toWire()) + .build(); + var ownerRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + NAMESPACE, + target.tenantUuid(), + "earth", + realm, + "main", + namespace, + "SHARED", + instance, + target.canonicalVersionUuid(), + 71L, + 73L, + 82L); + return new Fixture( + request, + target, + new CanonicalGameplayRosterOwnerReadEvidence( + ownerRequest, target.admissionPointerSnapshotDigest(), proof, policySet)); + } +} 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 324abdf114..531d015467 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 @@ -290,7 +290,9 @@ private JoinPublicProductionMembershipResponse correlateJoin( } if (response.getSuccess() && (!request.getPlayerContext().getAccountId().equals(response.getAccountId()) - || !request.getPlayerContext().getTenantId().equals(response.getTenantId()))) { + || !request.getPlayerContext().getTenantId().equals(response.getTenantId()) + || "JOINED".equals(response.getOutcomeCode()) + && !response.getGameplayAdmissionAllowed())) { return joinUnavailable(); } return response; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java new file mode 100644 index 0000000000..2ffb11db40 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java @@ -0,0 +1,338 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; + +/** + * Manually composed Account PLAYER_ADMISSION read. The caller supplies a verified first-party + * connect context and live LOGIN custody; this client contributes no admission decision or hold. + */ +public final class AccountPlayerAdmissionEntitlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceBlockingStub> { + private final String namespace; + private final String expectedAccountPeer; + private final Clock clock; + + public AccountPlayerAdmissionEntitlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String workloadNamespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tls, "Player-admission entitlement read"), + channels, + AccountPlayerAdmissionEntitlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Fixed Game Session workload namespace required"); + } + this.namespace = workloadNamespace; + this.expectedAccountPeer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + this.clock = Objects.requireNonNull(clock, "Clock required"); + } + + /** Initializes this workflow-owned client outside any ambient SQL transaction. */ + public void init() throws IOException { + requireNoAmbientSql( + "Player-admission entitlement client initialization requires no ambient SQL"); + initOnce("Player-admission entitlement client is closed", "Account read unavailable"); + } + + /** + * Reads the exact current Account value for one verified first-party scope and LOGIN result. The + * token is disclosed only by the generated request after exact same-namespace Account mTLS peer + * verification. This read supplies no World hold and never persists LOGIN custody. + */ + public RuntimePlayerAdmissionEntitlementEvidence read( + FirstPartyConnectContext verifiedContext, + UUID readRequestId, + CanonicalGameplayLoginResult loginCustody, + BooleanSupplier loginCustodyCurrent) { + requireNoAmbientSql("Player-admission entitlement RPC requires no ambient SQL"); + Deadline overall = + Deadline.after( + RuntimePlayerAdmissionEntitlementGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + if (Context.current().getDeadline() != null) { + overall = overall.minimum(Context.current().getDeadline()); + } + if (!v4(readRequestId)) { + throw invalid(); + } + if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + if (overall.isExpired()) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + + var request = request(verifiedContext, readRequestId); + var login = requireLiveLogin(loginCustody, request.target().accountId()); + byte[] compactJwt = null; + try { + compactJwt = loginCustody.compactJwtBytes(); + if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + if (overall.isExpired()) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + if (!isBoundedAsciiJwt(compactJwt) || !matchesSha256(compactJwt, login.tokenSha256())) { + throw invalid(); + } + String compact = new String(compactJwt, StandardCharsets.US_ASCII); + var wireRequest = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, compact); + var stub = + requireInitializedStub("Account player-admission entitlement client is unavailable") + .withDeadline(overall) + .withMaxOutboundMessageSize( + RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withMaxInboundMessageSize( + RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + // Recheck immediately before invoking gRPC; the call credentials independently gate body + // release on the exact authenticated Account peer. + if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + if (overall.isExpired()) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + var response = stub.readPlayerAdmissionEntitlement(wireRequest); + if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + var evidence = RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response); + requireTargetBinding(evidence, verifiedContext); + requireLoginBinding(evidence, login); + if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + evidence.requireCurrentAt(clock.instant()); + return evidence; + } catch (StatusRuntimeException transport) { + throw failure(transport.getStatus().getCode()); + } finally { + if (compactJwt != null) { + Arrays.fill(compactJwt, (byte) 0); + } + } + } + + private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( + FirstPartyConnectContext context, UUID readRequestId) { + try { + if (context == null || !context.hasCompleteRoutingScope()) { + throw invalid(); + } + var claims = context.claims(); + var target = context.resolvedTarget(); + if (target == null + || !namespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || target.positiveDurableAbort()) { + throw invalid(); + } + UUID accountId = UUID.fromString(context.accountId()); + if (!v4(accountId) + || claims.expiresAtMillis() <= clock.millis() + || context.connectScopeId() == null + || context.connectScopeId().isBlank()) { + throw invalid(); + } + var selector = + new RetainedTargetSelector( + readRequestId, + accountId, + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + selector, context.connectScopeId()); + } catch (RuntimeException invalidContext) { + throw invalid(); + } + } + + private CanonicalGameplayLoginResult.NonSecretEvidence requireLiveLogin( + CanonicalGameplayLoginResult custody, UUID expectedAccount) { + try { + if (custody == null) { + throw invalid(); + } + var evidence = custody.evidence(); + long now = clock.instant().getEpochSecond(); + if (evidence == null + || !expectedAccount.equals(evidence.accountId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(evidence.tokenProfile()) + || evidence.issuedAtEpochSecond() > now + || evidence.notBeforeEpochSecond() > now + || evidence.expiresAtEpochSecond() <= now) { + throw invalid(); + } + return evidence; + } catch (RuntimeException invalidCustody) { + throw invalid(); + } + } + + private static void requireLoginBinding( + RuntimePlayerAdmissionEntitlementEvidence evidence, + CanonicalGameplayLoginResult.NonSecretEvidence login) { + Object rawSources = evidence.fields().get("sourceReferences"); + if (!(rawSources instanceof Map sources) + || !login.tokenJti().toString().equals(sources.get("callerTokenJti")) + || !login.tokenSha256().equals(sources.get("callerTokenSha256")) + || !login.callerContextId().toString().equals(sources.get("callerContextId"))) { + throw invalid(); + } + } + + private static void requireTargetBinding( + RuntimePlayerAdmissionEntitlementEvidence evidence, FirstPartyConnectContext context) { + CanonicalPlayableTarget target = context.resolvedTarget(); + Object rawTarget = evidence.fields().get("target"); + Object rawSources = evidence.fields().get("sourceReferences"); + if (!(rawTarget instanceof Map actual) + || !(rawSources instanceof Map sources) + || !"PUBLIC_PRODUCTION".equals(actual.get("targetClass")) + || !"PRESEEDED_ONLY".equals(actual.get("characterCreationPolicy")) + || !target.targetNamespace().equals(actual.get("targetNamespace")) + || !target.canonicalTenantId().toString().equals(actual.get("tenantId")) + || !target.tenantSlug().equals(actual.get("tenantSlug")) + || !target.worldSlug().equals(actual.get("worldSlug")) + || !target.realmId().toString().equals(actual.get("realmId")) + || !target.realmSlug().equals(actual.get("realmSlug")) + || !target + .playableStateNamespaceId() + .toString() + .equals(actual.get("playableStateNamespaceId")) + || !target.playableStateScope().equals(actual.get("playableStateScope")) + || !target.canonicalGameInstanceId().toString().equals(actual.get("gameInstanceId")) + || !target.canonicalVersionId().toString().equals(actual.get("canonicalVersionId")) + || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) + || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion")) + || !Long.toString(target.activeWorldEpoch()).equals(actual.get("activeWorldEpoch")) + || !Instant.ofEpochMilli(context.claims().expiresAtMillis()) + .toString() + .equals(actual.get("connectScopeExpiresAt")) + || !target + .admissionPointerSnapshotDigest() + .equals(sources.get("admissionPointerSnapshotDigest")) + || !target.ownerProofDigest().equals(sources.get("gameSessionOwnerProofDigest"))) { + throw invalid(); + } + } + + private boolean isBoundedAsciiJwt(byte[] bytes) { + if (bytes == null + || bytes.length == 0 + || bytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + return false; + } + for (byte value : bytes) { + if (value < 0x21 || value > 0x7e) { + return false; + } + } + return true; + } + + private static boolean matchesSha256(byte[] value, String expected) { + byte[] digest = null; + try { + digest = MessageDigest.getInstance("SHA-256").digest(value); + return HexFormat.of().formatHex(digest).equals(expected); + } catch (NoSuchAlgorithmException unavailable) { + return false; + } finally { + if (digest != null) { + Arrays.fill(digest, (byte) 0); + } + } + } + + private static boolean current(BooleanSupplier custodyCurrent) { + try { + return custodyCurrent != null && custodyCurrent.getAsBoolean(); + } catch (RuntimeException unavailable) { + return false; + } + } + + private static boolean v4(UUID value) { + return value != null && value.version() == 4 && value.variant() == 2; + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceBlockingStub + buildStub(ManagedChannel channel) { + return AccountPlayerAdmissionEntitlementReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedAccountPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)) + .withCompression("gzip"); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Exact live LOGIN custody and verified player-admission scope required"); + } + + private static StatusRuntimeException failure(Status.Code code) { + return Status.fromCode(code) + .withDescription("Account player-admission entitlement read did not complete") + .asRuntimeException(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java index d23c662859..4420a992ba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java @@ -123,6 +123,7 @@ public static void requirePositiveReply( || reply.hasError() || !reply.getSuccess() || !Set.of("JOINED", "ALREADY_ACTIVE").contains(reply.getOutcomeCode()) + || "JOINED".equals(reply.getOutcomeCode()) && !reply.getGameplayAdmissionAllowed() || !scope.evidence().accountId().toString().equals(reply.getAccountId()) || !scope.issued().target().tenantId().equals(reply.getTenantId()) || !reply.getMembershipId().matches("[1-9][0-9]{0,18}") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java index 0cbbd476c7..8896519782 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -294,6 +294,35 @@ void actualOwnerReadsCommittedExactRequestBeforeAccountAndRetainsPositiveReply() verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); } + @Test + void alreadyActiveNonAdmittingReceiptReplaysExactlyWithoutBecomingGameplayAdmission() { + var scope = realms(); + var response = + positive().toBuilder() + .setOutcomeCode("ALREADY_ACTIVE") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(8L) + .setMembershipAuthorityGeneration(4L) + .setReplayed(true) + .build(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(response); + + var completed = owner.join(original, verified, custody); + assertThat(completed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); + assertThat(completed.currentReply()).contains(response); + assertThat(completed.currentReply().orElseThrow().getGameplayAdmissionAllowed()).isFalse(); + var row = + dsl.fetchSingle( + "SELECT reply_bytes FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()); + assertThat(row.get("reply_bytes", byte[].class)).containsExactly(response.toByteArray()); + + var continuation = owner(repository, manager).join(original, verified, custody); + assertThat(continuation.requestId()).isEqualTo(completed.requestId()); + assertThat(continuation.currentReply()).contains(response); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + @Test void independentConnectionsAllocateOneFrozenWinnerAndOnlyOneDispatchClaim() throws Exception { realms(); @@ -799,6 +828,7 @@ private static JoinPublicProductionMembershipResponse positive() { .setMembershipId("90") .setMembershipVersion(3) .setMembershipAuthorityGeneration(1) + .setGameplayAdmissionAllowed(true) .build(); } 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 b10193f3d5..c7626068fe 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 @@ -369,6 +369,21 @@ void joinPreservesProducerSuccessAndReplayEvidence(String outcome) throws Except .buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @Test + void joinDoesNotAcceptJoinedOutcomeWithoutAdmissionFlag() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenReturn( + joinSuccess("JOINED", false).toBuilder().setGameplayAdmissionAllowed(false).build()); + + var result = join(fixture.client(), directTextContext()); + + assertThat(result.getSuccess()).isFalse(); + assertThat(result.getError().getCode()).isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + } + @Test void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Exception { var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); @@ -698,6 +713,7 @@ private static JoinPublicProductionMembershipResponse joinSuccess( .setMembershipVersion(12L) .setMembershipAuthorityGeneration(3L) .setReplayed(replayed) + .setGameplayAdmissionAllowed(true) .build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java new file mode 100644 index 0000000000..6c52655e22 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -0,0 +1,432 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** Controlled Account peer proof for credential release and canonical response binding. */ +@Timeout(90) +class AccountPlayerAdmissionEntitlementClientMtlsTest { + private static final String NAMESPACE = "firemud-test"; + private static final String GS_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String ACCOUNT_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + private static final String JWT = "a.b.c"; + private static final UUID LOGIN_REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID LOGIN_CONTEXT = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID LOGIN_JTI = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final Instant NOW = Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW + 1_000L); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Player admission entitlement client test CA", + new LoopbackMtlsTestPki.IdentitySpec("client", GS_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT_PEER, true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/account-service", true)); + } + + @Test + void exactAccountPeerReceivesCurrentLoginCredentialAndReturnsBoundCanonicalEvidence() + throws Exception { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + var result = client.read(context, READ_REQUEST, login, () -> true); + assertThat(result.fields()) + .containsEntry("variant", "PLAYER_ADMISSION") + .containsEntry("sourceKind", "NON_PAID_DEMO") + .containsEntry("membershipExists", false); + assertThat(calls).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + assertThat(observedPeer).hasValue(GS_PEER); + assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); + } finally { + stop(server); + } + } + + @Test + void sameCaWrongServiceAndNamespaceReceiveNoRequestCredential() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server(identity, calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + assertThat(observedPeer).hasValue(null); + } finally { + stop(server); + } + } + } + + @Test + void staleLoginCustodyDoesNotStartRpc() throws Exception { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> false)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.CANCELLED)); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + } finally { + stop(server); + } + } + + private static AccountPlayerAdmissionEntitlementClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new AccountPlayerAdmissionEntitlementClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + CLOCK); + } + + private static Server server( + String identity, + AtomicInteger calls, + AtomicReference observedJwt, + AtomicReference observedPeer, + FirstPartyConnectContext context, + CanonicalGameplayLoginResult.NonSecretEvidence login) + throws Exception { + var service = + new AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceImplBase() { + @Override + public void readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + observedPeer.set(peer == null ? null : peer.uri()); + try { + var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(request); + observedJwt.set(presented.initialLoginJwt()); + var evidence = evidence(presented.request(), context, login); + observer.onNext( + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( + presented.request(), evidence)); + observer.onCompleted(); + } catch (Exception malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Controlled Account fixture rejected request") + .asRuntimeException()); + } + } + }; + var serverIdentity = pki.identity(identity); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static FirstPartyConnectContext context() { + var fixture = new FirstPartyReceivingFixture(); + CanonicalPlayableTarget target = org.mockito.Mockito.spy(fixture.target()); + doReturn("PRESEEDED_ONLY").when(target).characterCreationPolicy(); + when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)).thenReturn(target); + return fixture.service.parse(fixture.token()).orElseThrow(); + } + + private static CanonicalGameplayLoginResult loginCustody() throws Exception { + var login = mock(CanonicalGameplayLoginResult.class); + String jwtSha256 = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(JWT.getBytes(StandardCharsets.US_ASCII))); + var evidence = + new CanonicalGameplayLoginResult.NonSecretEvidence( + FirstPartyReceivingFixture.ACCOUNT, + LOGIN_REQUEST, + LOGIN_CONTEXT, + LOGIN_JTI, + jwtSha256, + GameSessionAccountDelegationProfile.PROFILE, + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(60).getEpochSecond(), + "1", + "1", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY); + when(login.evidence()).thenReturn(evidence); + when(login.compactJwtBytes()).thenAnswer(invocation -> JWT.getBytes(StandardCharsets.US_ASCII)); + return login; + } + + private static RuntimePlayerAdmissionEntitlementEvidence evidence( + RuntimePlayerAdmissionEntitlementGrpcCodec.Request request, + FirstPartyConnectContext context, + CanonicalGameplayLoginResult.NonSecretEvidence login) + throws Exception { + CanonicalPlayableTarget retained = context.resolvedTarget(); + Instant scopeExpiry = Instant.ofEpochMilli(context.claims().expiresAtMillis()); + Instant scopeStarted = NOW.minusSeconds(10); + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", retained.targetNamespace()); + target.put("tenantId", retained.canonicalTenantId().toString()); + target.put("tenantSlug", retained.tenantSlug()); + target.put("worldSlug", retained.worldSlug()); + target.put("realmId", retained.realmId().toString()); + target.put("realmSlug", retained.realmSlug()); + target.put("playableStateNamespaceId", retained.playableStateNamespaceId().toString()); + target.put("playableStateScope", retained.playableStateScope()); + target.put("gameInstanceId", retained.canonicalGameInstanceId().toString()); + target.put("canonicalVersionId", retained.canonicalVersionId().toString()); + target.put("catalogRevision", Long.toString(retained.catalogRevision())); + target.put("pointerVersion", Long.toString(retained.pointerVersion())); + target.put("activeWorldEpoch", Long.toString(retained.activeWorldEpoch())); + target.put("evaluatedAt", scopeStarted.toString()); + target.put("connectScopeExpiresAt", scopeExpiry.toString()); + + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String field : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) { + facts.put(field, true); + } + facts.put( + "quotas", + Map.of( + "maxActiveSessions", "3", + "maxConcurrentGameInstances", "2", + "maxStorageBytes", "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + + Map sources = new LinkedHashMap<>(); + sources.put("callerTokenJti", login.tokenJti().toString()); + sources.put("callerTokenSha256", login.tokenSha256()); + sources.put("callerRegistryRecordSha256", "a".repeat(64)); + sources.put("callerCommitProofSha256", "b".repeat(64)); + sources.put("callerContextId", login.callerContextId().toString()); + sources.put("callerOperationId", LOGIN_REQUEST.toString()); + sources.put( + "callerTokenExpiresAt", Instant.ofEpochSecond(login.expiresAtEpochSecond()).toString()); + sources.put("paidReceiptValidUntil", null); + sources.put("scopeDigest", "sha256:" + "c".repeat(64)); + sources.put("entitlementSourceDigest", "sha256:" + "d".repeat(64)); + sources.put("admissionPointerSnapshotDigest", retained.admissionPointerSnapshotDigest()); + sources.put("gameSessionOwnerProofDigest", retained.ownerProofDigest()); + sources.put("publishedPolicySetDigest", "sha256:" + "e".repeat(64)); + sources.put("worldLifecycleDigest", "sha256:" + "f".repeat(64)); + sources.put("worldCaptureId", "77777777-7777-4777-8777-777777777777"); + sources.put("worldRowVersion", "0"); + + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.target().readRequestId(), + request.expectedGameSessionWorkload(), + request.connectScopeId(), + membership(request.target().accountId(), request.target().tenantId(), retained), + target, + facts, + sources, + NOW); + } + + private static Snapshot membership(UUID account, UUID tenant, CanonicalPlayableTarget target) + throws Exception { + UUID sourceRequest = UUID.fromString("88888888-8888-4888-8888-888888888888"); + String hash = "a".repeat(64); + String requestDigest = + GameTenantCreationDigest.requestDigest( + target.targetNamespace(), sourceRequest, target.worldSlug(), "World", null); + var freshTenant = + new FreshTenantCreationEvidence( + 1, + target.targetNamespace(), + sourceRequest, + sourceRequest, + requestDigest, + tenant, + 17, + target.worldSlug(), + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + target.targetNamespace(), + sourceRequest, + sourceRequest, + requestDigest, + tenant, + 17, + target.worldSlug(), + "NEW_GAME_ROW")); + var authorityRequest = + new TenantAuthorityEventV1Codec.AuthorityRequest( + sourceRequest, + "sha256:" + hash, + tenant, + freshTenant.creationRequestId(), + freshTenant.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + tenant, + sourceRequest, + "sha256:" + hash, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenant), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(sourceRequest), + "sha256:" + hash); + var event = TenantAuthorityEventV1Codec.seal(authorityRequest, freshTenant, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenant.toString(), "2"), + Map.of(tenant.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + tenant.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + account.toString(), + tenant.toString(), + false, + "MISSING", + false, + Map.of(tenant.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + account, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + account + "/" + tenant, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index f63063eb72..cf6604fcca 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -135,6 +135,35 @@ void positiveReplyPreservesTheFullPositiveAccountBigintBoundary() { .isEqualTo(response); } + @Test + void alreadyActiveNonAdmittingMembershipIsRetainedAsAnExactNonAdmissionReceipt() { + var f = new Fixture(); + var response = + positive().toBuilder() + .setOutcomeCode("ALREADY_ACTIVE") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(8L) + .setMembershipAuthorityGeneration(4L) + .setReplayed(true) + .build(); + + assertThat(DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isEqualTo(response); + assertThat(response.getGameplayAdmissionAllowed()).isFalse(); + assertThat(response.getMembershipVersion()).isEqualTo(8L); + assertThat(response.getMembershipAuthorityGeneration()).isEqualTo(4L); + } + + @Test + void joinedReceiptCannotClaimSuccessWithoutGameplayAdmission() { + var f = new Fixture(); + var response = positive().toBuilder().setGameplayAdmissionAllowed(false).build(); + + assertThatThrownBy( + () -> DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void frozenRequestKeepsTransportCorrelationSeparateFromProxyOriginalContextAndJoinIds() { var f = new Fixture(); @@ -642,6 +671,7 @@ private static JoinPublicProductionMembershipResponse positive() { .setMembershipId("90") .setMembershipVersion(3) .setMembershipAuthorityGeneration(1) + .setGameplayAdmissionAllowed(true) .build(); } From db54e9e575d8e48b108b968e2ac9db930cd30f0e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:20:33 +1300 Subject: [PATCH 02/66] docs: retain recurring CI log transport recovery evidence --- design/project-management/ai-observations.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ee2f1503db..b6c5a18c0b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -55,3 +55,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-03` (Pacific/Auckland): Physical issuer retirement lost a fresh Redis connection before mutation. - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. + +- `2026-11-03` (Pacific/Auckland): GitHub job-log connector closes transport during CI failure inspection. + - Repeated per-job connector requests failed with `Transport closed` for #3386 Validation and #3388 World/Python jobs while other metadata reads worked. One later #3388 per-job request succeeded during an active workflow, without explaining the failures; whole-run `gh run view --log` still refused before completion. Both #3389 Account jobs125829036896/125829037055 recurred. Read-only per-job `gh api` log retrieval recovered their bytes into private files; any ANSI-capable retrieval must write directly to the private file rather than a terminal. Cause remains unknown. Next: preserve exact request/transport diagnostics on recurrence and repair the connector; do not rerun CI or replace controller operations to recover logs. From ac9ef8528121a6c21898be4cacf0e652810fb048 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:38:40 +1300 Subject: [PATCH 03/66] feat: consume canonical direct text scope for entitlement reads --- .../game-session-service/api-contracts.md | 2 + .../player-access-and-session.md | 4 +- ...countPlayerAdmissionEntitlementClient.java | 153 +++++--- ...yerAdmissionEntitlementClientMtlsTest.java | 371 +++++++++++++++++- 4 files changed, 469 insertions(+), 61 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 6e1d7b0d8c..e46a9b2d32 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -16,6 +16,8 @@ The local [canonical NEW admission lease contract](../../system-architecture-ses The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). +The manually composed `AccountPlayerAdmissionEntitlementClient` consumes the distinct [Account player-admission entitlement purpose](../account-service/api-contracts.md#private-player-admission-entitlement-read). It accepts either a verified first-party connect context or an Account-issued canonical direct-text lobby scope inside its current LOGIN-custody callback. The direct-text read retains the exact original attempt, observed transport, target and Account-issued expiry; historical scope decoding does not authenticate custody. Both inputs share bounded peer-qualified transport, before/after currentness checks and exact response/LOGIN bindings. This source installs no custody, registers no handler and supplies no World hold or admission decision; current proof and unfinished runtime composition belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). + The source-first owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. `RunOwnedCanonicalLaunchPreparationOwner` exposes canonical fresh-association, catalog and `STARTING` creation with independent owner readback only through an explicit preparation call; it has no scheduler. The published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap and existing `GameInstanceServiceImpl` behavior remain until coherent canonical adoption, so this source-first path is not evidence that the current scheduled runtime allocates that canonical launch. Game Design source keys and Game Session's allocated private tenant/runtime keys remain separate. The published numeric fixture path has not been removed by this source-only split. This explicit canonical path establishes no canonical World materialization/activation, canonical first-`OPEN`, or canonical admission result. `GameSessionControlPlaneService.GetRunOwnedFixtureLaunchAssociation` is a fixed, default-off source read of that exact `STARTING` allocation. It authenticates the same-namespace World workload and retained recipient certificate before decoding caller selectors, then requires the original operation and policy-seal digest. It returns the exact owner-allocated identities and retained policy request/seal, not World lifecycle, first `OPEN`, Account membership or player authority. The transport bypasses bearer validation only for this method; its exact workload checks remain mandatory. The canonical evidence shape is owned by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence), with producer consequences in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) and candidate proof in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#canonical-fixture-launch-owner-stage). 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 86fe3320f6..0cb48fc38f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ Account initial/current/final creation owners, explicit initial billing-owner co ### Canonical billing and retention receiving -The receiving foundation retains numeric subscription rows in the original renamed heap as immutable, non-authorizing evidence (V1028), installs canonical UUID subscription intent/provider history (V1029), and retains complete provisioning/lifecycle schema (V1030), first-dispatch claims (V1032) and cancellation-resolution journals (V1036). Retained history remains useful only for conservative deletion blockers; it is never current entitlement authority. The manually composed provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation does not establish provider absence, transfer, a registered recovery route or closure of the accepted terminal-recovery Major. +The receiving foundation retains numeric subscription rows in the original renamed heap as immutable, non-authorizing evidence (V1028), installs canonical UUID subscription intent/provider history (V1029), and retains complete provisioning/lifecycle schema (V1030), first-dispatch claims (V1032) and cancellation-resolution journals (V1036). Retained history remains useful only for conservative deletion blockers; it is never current entitlement authority. The manually composed provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation prepares one allowed safe outcome. Coupled physical proof through genuine current Account authorization, fresh primary authentication and the guarded financial commit remains outstanding for the accepted terminal-recovery Major. Provider absence and transfer are separate outcomes; production/default registration remains held and is not a prerequisite to qualifying this unregistered component boundary. The current billing-owner tuple deliberately rejects unaudited updates. Fixture reconciliation preserves that refusal and unchanged row/xmin, stale owner version/generation capture refusal, and genuine payment-instrument advancement concurrency. Positive queued-create fencing after a real audited owner-transfer commit remains an obligation of the unimplemented transfer owner; constructed stale comparison inputs do not prove that transfer. @@ -22,7 +22,7 @@ The published foundation carrier #3389 deliberately leaves public facade and num The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1035 diagnostics and V1037 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). -Preserved source proof310 passes575selected Account units,318passes312facade units and two actual HTTP→Entity compositions,320passes42App PostgreSQL cases,321passes13first-JOIN cases,324passes22PLAYER_ADMISSION owner plus five shared cases, and335passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving343/345 establish793unique selected unit passes after correcting one obsolete first-only generic proof assertion;344passes109selected physical PostgreSQL/HTTP/composition cases without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main198/200 holds remain. Remaining347static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The source is unpublished and does not close the accepted terminal-recovery Major. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. +Preserved source proof310 passes575selected Account units,318passes312facade units and two actual HTTP→Entity compositions,320passes42App PostgreSQL cases,321passes13first-JOIN cases,324passes22PLAYER_ADMISSION owner plus five shared cases, and335passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving343/345 establish793unique selected unit passes after correcting one obsolete first-only generic proof assertion;351passes169selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main198/200 holds remain. Remaining347static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused352transport proof passes all34mTLS client cases (31new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. The source is unpublished and does not close the accepted terminal-recovery Major. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java index 2ffb11db40..7d88cf4ae2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java @@ -18,6 +18,8 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; @@ -30,13 +32,16 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; /** - * Manually composed Account PLAYER_ADMISSION read. The caller supplies a verified first-party - * connect context and live LOGIN custody; this client contributes no admission decision or hold. + * Manually composed Account PLAYER_ADMISSION read. The caller supplies an owned canonical scope and + * live LOGIN custody; this client contributes no admission decision or hold. */ public final class AccountPlayerAdmissionEntitlementClient extends AbstractReloadingBlockingGrpcClient< @@ -82,6 +87,56 @@ public RuntimePlayerAdmissionEntitlementEvidence read( UUID readRequestId, CanonicalGameplayLoginResult loginCustody, BooleanSupplier loginCustodyCurrent) { + return read( + readRequestId, + loginCustody, + loginCustodyCurrent, + () -> request(verifiedContext, readRequestId), + () -> request(verifiedContext, readRequestId), + evidence -> + requireTargetBinding( + evidence, + verifiedContext.resolvedTarget(), + Instant.ofEpochMilli(verifiedContext.claims().expiresAtMillis()).toString())); + } + + /** + * Borrows an Account-issued direct-text lobby scope inside its owner's current custody callback. + * Retaining or decoding the scope never establishes that custody; this read installs no context. + */ + public RuntimePlayerAdmissionEntitlementEvidence read( + DirectTextAuthenticatedLobbyScope scope, + InitialGameplayLoginAttemptCoordinates original, + ObservedDirectTextTransport transport, + UUID readRequestId, + CanonicalGameplayLoginResult loginCustody, + BooleanSupplier loginCustodyCurrent) { + return read( + readRequestId, + loginCustody, + loginCustodyCurrent, + () -> { + if (scope == null) throw invalid(); + scope.requireCurrent(original, loginCustody, transport, clock); + }, + () -> + request( + scope.publicTarget(), + scope.evidence().accountId(), + scope.issued().connectScopeId(), + readRequestId), + evidence -> + requireTargetBinding( + evidence, scope.publicTarget(), scope.issued().connectScopeExpiresAt())); + } + + private RuntimePlayerAdmissionEntitlementEvidence read( + UUID readRequestId, + CanonicalGameplayLoginResult loginCustody, + BooleanSupplier loginCustodyCurrent, + Runnable requireScopeCurrent, + Supplier requestSource, + Consumer requireResponseTarget) { requireNoAmbientSql("Player-admission entitlement RPC requires no ambient SQL"); Deadline overall = Deadline.after( @@ -92,21 +147,17 @@ public RuntimePlayerAdmissionEntitlementEvidence read( if (!v4(readRequestId)) { throw invalid(); } - if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { - throw failure(Status.Code.CANCELLED); - } + requireCurrent(loginCustodyCurrent, requireScopeCurrent); if (overall.isExpired()) { throw failure(Status.Code.DEADLINE_EXCEEDED); } - var request = request(verifiedContext, readRequestId); + var request = requestSource.get(); var login = requireLiveLogin(loginCustody, request.target().accountId()); byte[] compactJwt = null; try { compactJwt = loginCustody.compactJwtBytes(); - if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { - throw failure(Status.Code.CANCELLED); - } + requireCurrent(loginCustodyCurrent, requireScopeCurrent); if (overall.isExpired()) { throw failure(Status.Code.DEADLINE_EXCEEDED); } @@ -124,22 +175,18 @@ public RuntimePlayerAdmissionEntitlementEvidence read( RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES); // Recheck immediately before invoking gRPC; the call credentials independently gate body // release on the exact authenticated Account peer. - if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { - throw failure(Status.Code.CANCELLED); - } + requireCurrent(loginCustodyCurrent, requireScopeCurrent); if (overall.isExpired()) { throw failure(Status.Code.DEADLINE_EXCEEDED); } var response = stub.readPlayerAdmissionEntitlement(wireRequest); - if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { - throw failure(Status.Code.CANCELLED); - } + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + requireLiveLogin(loginCustody, request.target().accountId()); var evidence = RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response); - requireTargetBinding(evidence, verifiedContext); + requireResponseTarget.accept(evidence); requireLoginBinding(evidence, login); - if (!current(loginCustodyCurrent) || Context.current().isCancelled()) { - throw failure(Status.Code.CANCELLED); - } + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + requireLiveLogin(loginCustody, request.target().accountId()); evidence.requireCurrentAt(clock.instant()); return evidence; } catch (StatusRuntimeException transport) { @@ -158,14 +205,6 @@ private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( throw invalid(); } var claims = context.claims(); - var target = context.resolvedTarget(); - if (target == null - || !namespace.equals(target.targetNamespace()) - || !"SHARED".equals(target.playableStateScope()) - || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) - || target.positiveDurableAbort()) { - throw invalid(); - } UUID accountId = UUID.fromString(context.accountId()); if (!v4(accountId) || claims.expiresAtMillis() <= clock.millis() @@ -173,28 +212,38 @@ private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( || context.connectScopeId().isBlank()) { throw invalid(); } - var selector = - new RetainedTargetSelector( - readRequestId, - accountId, - target.targetNamespace(), - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion()); - return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( - selector, context.connectScopeId()); + return request(context.resolvedTarget(), accountId, context.connectScopeId(), readRequestId); } catch (RuntimeException invalidContext) { throw invalid(); } } + private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( + CanonicalPlayableTarget target, UUID accountId, String connectScopeId, UUID readRequestId) { + if (target == null + || !namespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || target.positiveDurableAbort() + || !v4(accountId)) throw invalid(); + var selector = + new RetainedTargetSelector( + readRequestId, + accountId, + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request(selector, connectScopeId); + } + private CanonicalGameplayLoginResult.NonSecretEvidence requireLiveLogin( CanonicalGameplayLoginResult custody, UUID expectedAccount) { try { @@ -230,8 +279,9 @@ private static void requireLoginBinding( } private static void requireTargetBinding( - RuntimePlayerAdmissionEntitlementEvidence evidence, FirstPartyConnectContext context) { - CanonicalPlayableTarget target = context.resolvedTarget(); + RuntimePlayerAdmissionEntitlementEvidence evidence, + CanonicalPlayableTarget target, + String connectScopeExpiresAt) { Object rawTarget = evidence.fields().get("target"); Object rawSources = evidence.fields().get("sourceReferences"); if (!(rawTarget instanceof Map actual) @@ -254,9 +304,7 @@ private static void requireTargetBinding( || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion")) || !Long.toString(target.activeWorldEpoch()).equals(actual.get("activeWorldEpoch")) - || !Instant.ofEpochMilli(context.claims().expiresAtMillis()) - .toString() - .equals(actual.get("connectScopeExpiresAt")) + || !connectScopeExpiresAt.equals(actual.get("connectScopeExpiresAt")) || !target .admissionPointerSnapshotDigest() .equals(sources.get("admissionPointerSnapshotDigest")) @@ -301,6 +349,13 @@ private static boolean current(BooleanSupplier custodyCurrent) { } } + private static void requireCurrent(BooleanSupplier custodyCurrent, Runnable requireScopeCurrent) { + if (!current(custodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + requireScopeCurrent.run(); + } + private static boolean v4(UUID value) { return value != null && value.version() == 4 && value.variant() == 2; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index 6c52655e22..6ca0218ecb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -23,6 +23,7 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; @@ -30,9 +31,13 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; @@ -48,18 +53,25 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** Controlled Account peer proof for credential release and canonical response binding. */ @Timeout(90) @@ -76,6 +88,12 @@ class AccountPlayerAdmissionEntitlementClientMtlsTest { private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); private static final Instant NOW = Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW + 1_000L); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, LOGIN_CONTEXT, 1); + private static final ObservedDirectTextTransport TRANSPORT = + new ObservedDirectTextTransport( + "00042", UUID.fromString("99999999-9999-4999-8999-999999999999")); + private static final Instant DIRECT_SCOPE_EXPIRY = NOW.plusSeconds(25); @TempDir static Path directory; private static LoopbackMtlsTestPki.Pki pki; @@ -168,7 +186,288 @@ void staleLoginCustodyDoesNotStartRpc() throws Exception { } } + @Test + void directTextOwnedScopeUsesExactAccountExpiryAndCurrentLoginWithoutFirstPartyContext() + throws Exception { + var target = context().resolvedTarget(); + var borrowed = new ArrayList(); + var login = loginCustody(borrowed); + var scope = directTextScope(target, login, DIRECT_SCOPE_EXPIRY); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + DIRECT_SCOPE_EXPIRY, + login.evidence(), + (value, sources) -> {}, + () -> {}); + try (var client = client(server)) { + client.init(); + var result = client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true); + assertThat(result.fields()) + .containsEntry("verifiedConnectScopeId", "direct-text-owned-scope"); + assertThat(((Map) result.fields().get("target")).get("connectScopeExpiresAt")) + .isEqualTo(DIRECT_SCOPE_EXPIRY.toString()); + assertThat(calls).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + assertThat(observedPeer).hasValue(GS_PEER); + assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); + assertThat(borrowed) + .isNotEmpty() + .allSatisfy(bytes -> assertThat(bytes).containsOnly((byte) 0)); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "original-request", + "original-context", + "attempt-fence", + "transport-session", + "transport-proxy", + "stale-custody", + "throwing-custody", + "null-custody", + "custody-lost-before-rpc", + "closed-login", + "expired-login", + "expired-scope", + "wrong-namespace", + "private-scope", + "created-policy", + "durable-abort", + "read-correlation" + }) + void directTextInvalidOrStaleInputsDiscloseNoCredential(String change) throws Exception { + var target = context().resolvedTarget(); + switch (change) { + case "wrong-namespace" -> doReturn("other").when(target).targetNamespace(); + case "private-scope" -> doReturn("ISOLATED").when(target).playableStateScope(); + case "created-policy" -> doReturn("PLAYER_CREATED").when(target).characterCreationPolicy(); + case "durable-abort" -> doReturn(true).when(target).positiveDurableAbort(); + default -> {} + } + var login = loginCustody(); + var expiry = "expired-login".equals(change) ? NOW.plusSeconds(90) : DIRECT_SCOPE_EXPIRY; + var scope = directTextScope(target, login, expiry); + var original = + switch (change) { + case "original-request" -> + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), LOGIN_CONTEXT, 1); + case "original-context" -> + new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, UUID.randomUUID(), 1); + case "attempt-fence" -> + new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, LOGIN_CONTEXT, 2); + default -> ORIGINAL; + }; + var transport = + switch (change) { + case "transport-session" -> + new ObservedDirectTextTransport("42", TRANSPORT.proxyConnectionId()); + case "transport-proxy" -> new ObservedDirectTextTransport("00042", UUID.randomUUID()); + default -> TRANSPORT; + }; + var checks = new AtomicInteger(); + BooleanSupplier current = + switch (change) { + case "stale-custody" -> () -> false; + case "throwing-custody" -> + () -> { + throw new IllegalStateException("Controlled custody lost"); + }; + case "null-custody" -> null; + case "custody-lost-before-rpc" -> () -> checks.incrementAndGet() < 3; + default -> () -> true; + }; + if ("closed-login".equals(change)) { + when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Controlled closed LOGIN")); + } + Clock clientClock = + switch (change) { + case "expired-login" -> Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC); + case "expired-scope" -> Clock.fixed(DIRECT_SCOPE_EXPIRY, ZoneOffset.UTC); + default -> CLOCK; + }; + UUID selectedReadId = "read-correlation".equals(change) ? new UUID(0, 0) : READ_REQUEST; + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = + server("account", calls, observedJwt, observedPeer, context(), login.evidence()); + try (var client = client(server, clientClock)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, original, transport, selectedReadId, login, current)) + .isInstanceOf(RuntimeException.class); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + assertThat(observedPeer).hasValue(null); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void directTextWrongAccountPeerReceivesNoCredential(String identity) throws Exception { + var context = context(); + var login = loginCustody(); + var scope = directTextScope(context.resolvedTarget(), login, DIRECT_SCOPE_EXPIRY); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server(identity, calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "version", + "owner-proof", + "pointer-digest", + "scope-expiry", + "login-jti", + "login-hash", + "login-context" + }) + void directTextRejectsAuthenticatedResponseBindingDrift(String change) throws Exception { + var target = context().resolvedTarget(); + var login = loginCustody(); + var scope = directTextScope(target, login, DIRECT_SCOPE_EXPIRY); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + BiConsumer, Map> drift = + (value, sources) -> { + switch (change) { + case "version" -> value.put("canonicalVersionId", UUID.randomUUID().toString()); + case "owner-proof" -> + sources.put("gameSessionOwnerProofDigest", "sha256:" + "9".repeat(64)); + case "pointer-digest" -> sources.put("admissionPointerSnapshotDigest", "9".repeat(64)); + case "scope-expiry" -> + value.put("connectScopeExpiresAt", DIRECT_SCOPE_EXPIRY.plusSeconds(1).toString()); + case "login-jti" -> sources.put("callerTokenJti", UUID.randomUUID().toString()); + case "login-hash" -> sources.put("callerTokenSha256", "9".repeat(64)); + case "login-context" -> sources.put("callerContextId", UUID.randomUUID().toString()); + default -> throw new IllegalArgumentException(change); + } + }; + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + DIRECT_SCOPE_EXPIRY, + login.evidence(), + drift, + () -> {}); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(calls).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"custody", "scope-expiry", "login-expiry", "closed-login"}) + void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { + var target = context().resolvedTarget(); + var login = loginCustody(); + var expiry = "login-expiry".equals(change) ? NOW.plusSeconds(90) : DIRECT_SCOPE_EXPIRY; + var scope = directTextScope(target, login, expiry); + var current = new AtomicBoolean(true); + var clockTime = new AtomicReference<>(NOW); + Clock movingClock = mock(Clock.class); + when(movingClock.instant()).thenAnswer(invocation -> clockTime.get()); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Runnable afterRead = + () -> { + switch (change) { + case "custody" -> current.set(false); + case "scope-expiry" -> clockTime.set(DIRECT_SCOPE_EXPIRY); + case "login-expiry" -> clockTime.set(NOW.plusSeconds(60)); + case "closed-login" -> + when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Closed LOGIN")); + default -> throw new IllegalArgumentException(change); + } + }; + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + expiry, + login.evidence(), + (value, sources) -> {}, + afterRead); + try (var client = client(server, movingClock)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, current::get)) + .isInstanceOf(RuntimeException.class); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + private static DirectTextAuthenticatedLobbyScope directTextScope( + CanonicalPlayableTarget target, CanonicalGameplayLoginResult login, Instant expiry) { + return new DirectTextAuthenticatedLobbyScope( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + InitialGameplayLoginContextState.installed(ORIGINAL, login), + TRANSPORT, + target, + DirectTextIssuedConnectScope.fromAccountResponse( + FirstPartyReceivingFixture.ACCOUNT.toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("direct-text-owned-scope") + .setEvaluatedAt(NOW.minusSeconds(10).toString()) + .setConnectScopeExpiresAt(expiry.toString()) + .build(), + CLOCK)); + } + private static AccountPlayerAdmissionEntitlementClient client(Server server) throws Exception { + return client(server, CLOCK); + } + + private static AccountPlayerAdmissionEntitlementClient client(Server server, Clock clock) + throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); return new AccountPlayerAdmissionEntitlementClient( @@ -176,7 +475,7 @@ private static AccountPlayerAdmissionEntitlementClient client(Server server) thr pki.clientProperties(directory, pki.identity("client")), new GrpcChannelFactory(), NAMESPACE, - CLOCK); + clock); } private static Server server( @@ -187,6 +486,29 @@ private static Server server( FirstPartyConnectContext context, CanonicalGameplayLoginResult.NonSecretEvidence login) throws Exception { + return server( + identity, + calls, + observedJwt, + observedPeer, + context.resolvedTarget(), + Instant.ofEpochMilli(context.claims().expiresAtMillis()), + login, + (value, sources) -> {}, + () -> {}); + } + + private static Server server( + String identity, + AtomicInteger calls, + AtomicReference observedJwt, + AtomicReference observedPeer, + CanonicalPlayableTarget target, + Instant scopeExpiry, + CanonicalGameplayLoginResult.NonSecretEvidence login, + BiConsumer, Map> drift, + Runnable afterRead) + throws Exception { var service = new AccountPlayerAdmissionEntitlementReadServiceGrpc .AccountPlayerAdmissionEntitlementReadServiceImplBase() { @@ -200,7 +522,8 @@ public void readPlayerAdmissionEntitlement( try { var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(request); observedJwt.set(presented.initialLoginJwt()); - var evidence = evidence(presented.request(), context, login); + var evidence = evidence(presented.request(), target, scopeExpiry, login, drift); + afterRead.run(); observer.onNext( RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( presented.request(), evidence)); @@ -241,6 +564,10 @@ private static FirstPartyConnectContext context() { } private static CanonicalGameplayLoginResult loginCustody() throws Exception { + return loginCustody(new ArrayList<>()); + } + + private static CanonicalGameplayLoginResult loginCustody(List borrowed) throws Exception { var login = mock(CanonicalGameplayLoginResult.class); String jwtSha256 = HexFormat.of() @@ -260,21 +587,44 @@ private static CanonicalGameplayLoginResult loginCustody() throws Exception { NOW.plusSeconds(60).getEpochSecond(), "1", "1", - ByteString.EMPTY, - ByteString.EMPTY, - ByteString.EMPTY); + canonical(GameSessionAccountDelegationProfile.authorityTuple(1, 1)), + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + FirstPartyReceivingFixture.ACCOUNT, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/firemud-account-service", + "outboxSequence", + "0"))), + canonical(List.of())); when(login.evidence()).thenReturn(evidence); - when(login.compactJwtBytes()).thenAnswer(invocation -> JWT.getBytes(StandardCharsets.US_ASCII)); + when(login.compactJwtBytes()) + .thenAnswer( + invocation -> { + byte[] bytes = JWT.getBytes(StandardCharsets.US_ASCII); + borrowed.add(bytes); + return bytes; + }); return login; } + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value))); + } + private static RuntimePlayerAdmissionEntitlementEvidence evidence( RuntimePlayerAdmissionEntitlementGrpcCodec.Request request, - FirstPartyConnectContext context, - CanonicalGameplayLoginResult.NonSecretEvidence login) + CanonicalPlayableTarget retained, + Instant scopeExpiry, + CanonicalGameplayLoginResult.NonSecretEvidence login, + BiConsumer, Map> drift) throws Exception { - CanonicalPlayableTarget retained = context.resolvedTarget(); - Instant scopeExpiry = Instant.ofEpochMilli(context.claims().expiresAtMillis()); Instant scopeStarted = NOW.minusSeconds(10); Map target = new LinkedHashMap<>(); target.put("targetClass", "PUBLIC_PRODUCTION"); @@ -335,6 +685,7 @@ private static RuntimePlayerAdmissionEntitlementEvidence evidence( sources.put("worldLifecycleDigest", "sha256:" + "f".repeat(64)); sources.put("worldCaptureId", "77777777-7777-4777-8777-777777777777"); sources.put("worldRowVersion", "0"); + drift.accept(target, sources); return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( request.target().readRequestId(), From b5130299e30e2fe76eb655684c8c2b2fef5e3692 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:56:11 +1300 Subject: [PATCH 04/66] Include both canonical creation policies in public world discovery --- .../game-session-service/api-contracts.md | 2 +- .../player-access-and-session.md | 4 ++- ...AccountPublicBootstrapWorldsOwnerTest.java | 29 +++++++++++++++- ...ameplayAdmissionDecisionReadGrpcCodec.java | 5 +-- ...layAdmissionDecisionReadGrpcCodecTest.java | 21 ++++++++++-- ...yAdmissionDecisionReadGrpcServiceTest.java | 33 ++++++++++++++++++- 6 files changed, 86 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index e46a9b2d32..2dd4a705a6 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -66,7 +66,7 @@ Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId} ### Public-production bootstrap target collection read -The manually composed, unregistered `CanonicalGameplayAdmissionDecisionReadService.ListVisiblePublicProductionAdmissionTargets` is an Account-purpose point-in-time source read. It accepts only the exact same-namespace Account workload over mTLS, without propagated player context or an ambient SQL transaction. The closed request and response are defined by [`canonical_gameplay_admission_decision_read.proto`](../../../../protos/game-session/v1/canonical_gameplay_admission_decision_read.proto). The source is the complete current canonical visible public-production target collection from `CanonicalPlayerRouteReadService`, restricted to `SHARED` targets with `PRESEEDED_ONLY`; each returned target retains the canonical target and committed owner proof needed by Account for pre-scope discovery. +The manually composed, unregistered `CanonicalGameplayAdmissionDecisionReadService.ListVisiblePublicProductionAdmissionTargets` is an Account-purpose point-in-time source read. It accepts only the exact same-namespace Account workload over mTLS, without propagated player context or an ambient SQL transaction. The closed request and response are defined by [`canonical_gameplay_admission_decision_read.proto`](../../../../protos/game-session/v1/canonical_gameplay_admission_decision_read.proto). The source is the complete current canonical visible public-production target collection from `CanonicalPlayerRouteReadService`, restricted to `SHARED` targets with either canonical `PRESEEDED_ONLY` or `PLAYER_CREATED` creation policy; each returned target retains the canonical target and committed owner proof needed by Account for pre-scope discovery. The canonical catalog and route owner permit one public-production target per tenant; duplicate tenant identities/slugs or realm identities refuse rather than selecting a realm. Unknown policies, isolated/private targets and incomplete evidence refuse the whole collection. This complete discovery collection does not relax policy-specific target selection, roster or admission methods. Game Session validates the complete first collection, independently rereads the complete collection, and returns it only if an order-independent comparison finds the exact target values and membership unchanged. An authenticated empty collection is valid. Missing or unavailable authority, malformed or ambiguous targets, changed sources, and an oversized response do not become an empty or partial success. The request is bounded to 16 KiB, each target to 64 KiB, and the complete response to 4 MiB; there is no pagination or truncation, and the Account client uses a five-second deadline. This read supplies neither a fresh World lifecycle read or hold nor caller authorization, scope issuance, membership, JOIN, or gameplay admission. Account owns entitlement filtering and result semantics; target selection and subsequent strict source reads remain separate. 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 888a8d5aa7..8d4cae0b6d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -26,6 +26,8 @@ Preserved source proof310 passes575selected Account units,318passes312facade uni Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. +The complete public WORLDS collection now accepts both canonical `SHARED` creation policies, `PRESEEDED_ONLY` and `PLAYER_CREATED`, without filtering a represented world or changing the one-public-target-per-tenant authority. Unknown/private policies, duplicate identities, changed collections and expired entitlement still refuse. The separate policy-specific source, roster and admission methods keep their own restrictions. This closes the accepted CLI1 discovery observation routed from #3383 in the existing public facade receiver. Proof379 passes all 341 focused cases with zero failures/errors/skips: the full 296-case Common Security suite, 33 Game Session collection/source cases and 12 Account WORLDS cases, including complete mixed-policy readback and deterministic entitlement filtering. Enabled affected analysis, formatting and docs pass. These are controlled component proofs, not successful public runtime or registration/custody qualification. + ### Lifecycle-bound private realm-grant source preparation Local source includes [`RealmGrantMutation`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/RealmGrantMutation.java), the [shared grant scope codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodec.java), the [grant event codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1Codec.java), and Account's [lifecycle-bound grant repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantRepository.java) with [migration V1027.2](../../../services/account-service/src/main/resources/db/migration/V1027.2__lifecycle_bound_realm_grant_authority.sql). The composed read uses [`AccountCurrentLifecycleRealmGrantReadOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwner.java), [`GameSessionCurrentPrivatePlaytestLifecycleReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClient.java), and the shared [`CurrentPrivatePlaytestLifecycleReadGrpcCodec`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodec.java). Canonical grant/lifecycle behavior remains in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md), with the Game Session handoff recorded in [Realm Routing](./realm-routing-and-playable-state.md#initial-fresh-lifecycle-preparation). @@ -36,7 +38,7 @@ Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 [`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. -The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and returns only the complete visible public-production `SHARED`/`PRESEEDED_ONLY` target collection. Its owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. +The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and returns the complete visible public-production `SHARED` target collection with `PRESEEDED_ONLY` or `PLAYER_CREATED` policy. Its owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. [`AccountPublicBootstrapWorldsOwnerTest`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [`AccountPublicBootstrapEntitlementOwnerTest`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), the [Account target client test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), and the focused [Game Session collection-read](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java) and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java) cover the manually composed discovery source. Proof163/166 executes 165 selected units (17 shared codec, 44 Game Session and 104 Account); proof164/166 executes seven real Account PostgreSQL discovery cases, including successful deterministic filtering, genuine source-head mutation, missing source, expiry, ambiguity, target change and caller-currentness loss. Proof167 qualifies the nullable transaction-definition fixture and Account test static analysis; proof168 adds three real loopback mTLS client cases for exact peer identity, authenticated empty collection and malformed/correlation refusal. These source tests use actual Account DEMO SQL and a controlled complete Game Session response; the loopback mTLS tests use a controlled Game Session server. Neither establishes the whole authenticated source chain or deployment custody. Proof178 passes 189 selected unit/loopback cases and 13 physical cases, with affected static, formatting and documentation checks; the physical cases include the seven discovery cases, three pre-V1028 scope cases and three final-admission composition cases. The latter use a controlled World capture, not a qualified end-to-end World source chain. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java index 76b4b23376..0f27081d8a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java @@ -84,6 +84,23 @@ void returnsSortedPublicWorldsAfterCompleteStableReorderedSourceAndFinalCallerCh verify(f.sessions, times(2)).isAccountSessionActive(ACCOUNT_ID, TOKEN); } + @Test + void mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery() { + Fixture f = new Fixture(); + var seeded = target(TENANT_A, "tenant-a", "seeded", "Seeded", 1); + var created = target(TENANT_B, "tenant-b", "created", "Created", 1, "PLAYER_CREATED"); + f.stubTargetReads(List.of(seeded, created), List.of(created, seeded)); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(30))); + when(f.entitlements.evaluate(TENANT_B)) + .thenReturn(evaluation(TENANT_B, true, NOW.plusSeconds(30))); + assertThat(f.owner.listWorlds(TOKEN)) + .containsExactly( + new BootstrapWorldDto("created", "Created"), new BootstrapWorldDto("seeded", "Seeded")); + verify(f.entitlements, times(1)).evaluate(TENANT_A); + verify(f.entitlements, times(1)).evaluate(TENANT_B); + } + @Test void denialFiltersGameplayUnavailableTenantButDoesNotRequireJoinEligibility() { Fixture f = new Fixture(); @@ -262,6 +279,16 @@ private static Evaluation evaluation(UUID tenantId, boolean available, Instant v private static Target target( UUID tenantId, String tenantSlug, String worldSlug, String displayName, long pointerVersion) { + return target(tenantId, tenantSlug, worldSlug, displayName, pointerVersion, "PRESEEDED_ONLY"); + } + + private static Target target( + UUID tenantId, + String tenantSlug, + String worldSlug, + String displayName, + long pointerVersion, + String creationPolicy) { String suffix = tenantId.toString(); return new Target( "prod", @@ -301,7 +328,7 @@ private static Target target( OwnerProofOutcome.COMMITTED, false, NOW, - "PRESEEDED_ONLY"); + creationPolicy); } private static Account account(long id) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java index 5d382dce16..22bc86bd2b 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java @@ -188,14 +188,15 @@ public static VisiblePublicProductionTargets fromDiscoveryResponse( Target target = parseTargetEvidence(wire); if (!expected.targetNamespace().equals(target.targetNamespace()) || !"SHARED".equals(target.playableStateScope()) - || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || !("PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || "PLAYER_CREATED".equals(target.characterCreationPolicy())) || target.ownerProofOutcome() != OwnerProofOutcome.COMMITTED || target.positiveDurableAbort() || !tenants.add(target.canonicalTenantId()) || !tenantSlugs.add(target.tenantSlug()) || !realms.add(target.realmId())) { throw invalid( - "Discovery requires unique current public SHARED PRESEEDED owner targets"); + "Discovery requires unique current public SHARED owner targets with a supported creation policy"); } return target; }) diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java index 2d1298723e..48491eb874 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java @@ -96,6 +96,24 @@ void discoveryRoundTripsCompleteOwnerTargetsAndAuthenticatedEmptyCollection() { .isEmpty(); } + @Test + void discoveryCarriesBothSupportedPublicCreationPoliciesWithoutChangingTargetEvidence() { + for (String policy : List.of("PRESEEDED_ONLY", "PLAYER_CREATED")) { + var current = target(lease(), policy); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + DECISION_ID, current.targetNamespace()); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(current)); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, response) + .targets()) + .containsExactly(current); + } + } + @Test void discoveryRejectsOpenRequestShapeAndChangedResponseCorrelation() { var request = @@ -168,8 +186,7 @@ void discoveryRejectsDuplicateTenantAuthorityAndUnsupportedOrIncompleteTargets() .setCurrentTargets(0, wire.toBuilder().setPlayableStateScope(0, "ISOLATED")) .build(), response.toBuilder() - .setCurrentTargets( - 0, wire.toBuilder().setCharacterCreationPolicy(0, "PLAYER_CREATED")) + .setCurrentTargets(0, wire.toBuilder().setCharacterCreationPolicy(0, "UNSUPPORTED")) .build(), response.toBuilder() .setCurrentTargets(0, wire.toBuilder().clearCanonicalGameInstanceUuid()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index c110d8afdd..1e7b90494e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -217,7 +218,37 @@ private static void assertDiscoveryFailure( verify(observer, never()).onCompleted(); } + @Test + void discoveryReturnsCompleteMixedPolicyTargetsWithStableIndependentReread() { + var seeded = discoveryTarget("seeded", "Seeded world"); + var created = discoveryTarget("created", "Created world", "PLAYER_CREATED"); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()) + .thenReturn(List.of(seeded, created), List.of(created, seeded)); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + var captured = + ArgumentCaptor.forClass(ListVisiblePublicProductionAdmissionTargetsResponse.class); + verify(observer).onNext(captured.capture()); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(discoveryRequest()); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, captured.getValue()) + .targets()) + .extracting(target -> target.characterCreationPolicy()) + .containsExactly("PLAYER_CREATED", "PRESEEDED_ONLY"); + verify(routes, times(2)).readVisiblePublicProductionTargets(); + verify(observer).onCompleted(); + } + private static CanonicalPlayableTarget discoveryTarget(String slug, String displayName) { + return discoveryTarget(slug, displayName, "PRESEEDED_ONLY"); + } + + private static CanonicalPlayableTarget discoveryTarget( + String slug, String displayName, String creationPolicy) { UUID tenant = UUID.nameUUIDFromBytes(("tenant-" + slug).getBytes(StandardCharsets.UTF_8)); UUID realm = UUID.nameUUIDFromBytes(("realm-" + slug).getBytes(StandardCharsets.UTF_8)); UUID namespace = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); @@ -277,7 +308,7 @@ private static CanonicalPlayableTarget discoveryTarget(String slug, String displ CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, false, Instant.parse("2026-10-25T00:00:00Z"), - "PRESEEDED_ONLY"); + creationPolicy); } @Test From dc7d26cafaa054054bcc2a4d313290a2cc3b3d67 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:24:10 +1300 Subject: [PATCH 05/66] ci: keep service documentation out of runtime module selection --- .github/scripts/classify-change-scope.cjs | 13 ++- .../scripts/classify-change-scope.test.cjs | 90 +++++++++++++++++++ 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index 02d5efe5e6..f18905e400 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -160,9 +160,18 @@ function moduleForFile(file) { function classifyChangeScope(inputFiles, options = {}) { const files = [...new Set(inputFiles)].sort(); const forceAll = options.forceAll === true; + // Known service documentation retains docs proof without selecting runtime modules. + // Unknown service paths and every non-documentation input remain fail closed. + const moduleInputFiles = files.filter( + (file) => + !(file.startsWith("services/") && + moduleForFile(file) !== null && + isDocumentation(file) && + isLightweightEligible(file)), + ); const runAll = forceAll || - files.some( + moduleInputFiles.some( (file) => SHARED_FILES.has(file) || (SHARED_PREFIXES.some((prefix) => file.startsWith(prefix)) && @@ -176,7 +185,7 @@ function classifyChangeScope(inputFiles, options = {}) { ALL_SERVICES.forEach((service) => affectedServices.add(service)); ALL_MODULES.forEach((module) => affectedModules.add(module)); } else { - for (const file of files) { + for (const file of moduleInputFiles) { const module = moduleForFile(file); if (module !== null) { affectedModules.add(module); diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 5bd0855abc..1b99e51091 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -41,6 +41,96 @@ test("documentation-only changes use the lightweight path", () => { assert.deepEqual(result.affectedServices, []); }); +test("known service and shared-module documentation selects no heavy module proof", async () => { + for (const module of ALL_MODULES.filter((module) => module !== "load-testing")) { + for (const path of [`services/${module}/README.md`, `services/${module}/design/README.md`]) { + const result = await classifyGithubFiles([path], 1); + + assert.equal(result.runAll, false, path); + assert.equal(result.lightweightOnly, true, path); + assert.equal(result.docsChanged, true, path); + assert.deepEqual(result.affectedModules, [], path); + assert.deepEqual(result.affectedServices, [], path); + assert.deepEqual(result.bootableModules, [], path); + } + } +}); + +test("service documentation does not add modules to a cumulative runtime diff", async () => { + const result = await classifyGithubFiles([ + "services/common-platform-core/README.md", + "services/world-management-service/README.md", + "services/account-service/src/main/java/example/Account.java", + ], 3); + + assert.equal(result.runAll, false); + assert.equal(result.lightweightOnly, false); + assert.equal(result.docsChanged, true); + assert.deepEqual(result.affectedModules, ["account-service"]); + assert.deepEqual(result.affectedServices, ["account-service"]); + assert.deepEqual(result.bootableModules, ["account-service"]); +}); + +test("service docs never suppress shared runtime, toolchain, or workflow inputs", () => { + for (const path of [ + "services/common-platform-core/src/main/java/example/Shared.java", + "gradle/libs.versions.toml", + "protos/account.proto", + ".github/workflows/ci.yml", + ]) { + const result = classifyChangeScope(["services/account-service/README.md", path]); + + assert.equal(result.runAll, true, path); + assert.equal(result.lightweightOnly, false, path); + assert.deepEqual(result.affectedModules, ALL_MODULES, path); + } +}); + +test("forced and incomplete service-documentation inventories retain complete proof", async () => { + const path = "services/common-platform-core/README.md"; + const forced = classifyChangeScope([path], { forceAll: true }); + assert.equal(forced.runAll, true); + assert.equal(forced.lightweightOnly, false); + assert.deepEqual(forced.affectedModules, ALL_MODULES); + + for (const count of [undefined, 2, "1"]) { + const result = await classifyGithubFiles([path], count); + assert.equal(result.runAll, true); + assert.equal(result.lightweightOnly, false); + assert.deepEqual(result.affectedModules, ALL_MODULES); + } + const malformed = await classifyGithubFiles([{ filename: path, previous_filename: "" }], 1); + assert.equal(malformed.runAll, true); + assert.deepEqual(malformed.affectedModules, ALL_MODULES); +}); + +test("unknown-service documentation still fails closed", async () => { + const result = await classifyGithubFiles(["services/unknown-service/README.md"], 1); + + assert.equal(result.runAll, true); + assert.deepEqual(result.affectedModules, ALL_MODULES); + assert.deepEqual(result.affectedServices, ALL_SERVICES); +}); + +test("renaming runtime inputs to service docs retains their old runtime selection", async () => { + for (const [previous, expectedModules, runAll] of [ + ["services/account-service/src/main/java/Account.java", ["account-service"], false], + ["services/game-session-service/src/main/java/Session.java", + ["game-session-service", "account-service"], false], + ["services/common-platform-core/src/main/java/Shared.java", ALL_MODULES, true], + ["services/unknown-service/src/main/java/Owner.java", ALL_MODULES, true], + ]) { + const result = await classifyGithubFiles([{ + filename: "services/account-service/README.md", + previous_filename: previous, + }], 1); + + assert.equal(result.runAll, runAll, previous); + assert.equal(result.lightweightOnly, false, previous); + assert.deepEqual(result.affectedModules, expectedModules, previous); + } +}); + test("ERD generation remains docs-affecting but never uses the lightweight path", () => { const result = classifyChangeScope(["dev-tools/docs/generate-erd.sh"]); From 4aa855acc95df1b8598c8707b1f8cb9bd3c9b106 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:39:12 +1300 Subject: [PATCH 06/66] Keep physical roster Docker proof in the fixture contract --- dev-tools/tests/testcontainers-disabled-contract.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/testcontainers-disabled-contract.sh b/dev-tools/tests/testcontainers-disabled-contract.sh index 51159513ab..f7f21be261 100644 --- a/dev-tools/tests/testcontainers-disabled-contract.sh +++ b/dev-tools/tests/testcontainers-disabled-contract.sh @@ -4,6 +4,7 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" SAGA_TEST="$ROOT_DIR/services/common-saga/src/test/java/integration/net/firedevops/firemud/common/saga/persistence/SagaPersistenceRepositoryIntegrationTest.java" IN_PROCESS_TEST="services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionCrossServiceIntegrationTest.java" +POSTGRES_MTLS_TEST="services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java" grep -Eq '^@Testcontainers\(disabledWithoutDocker = true\)$' "$SAGA_TEST" if grep -Eq 'POSTGRES\.(start|stop)\(' "$SAGA_TEST"; then @@ -17,7 +18,10 @@ while IFS= read -r -d '' java_file; do bare_annotations+=("${java_file#"$ROOT_DIR/"}") fi done < <(find "$ROOT_DIR/services" -type f -name '*.java' -print0) -if ((${#bare_annotations[@]} != 1)) || [[ "${bare_annotations[0]}" != "$IN_PROCESS_TEST" ]]; then +expected_bare_annotations=("$IN_PROCESS_TEST" "$POSTGRES_MTLS_TEST") +if ! diff -u \ + <(printf '%s\n' "${expected_bare_annotations[@]}" | LC_ALL=C sort) \ + <(printf '%s\n' "${bare_annotations[@]}" | LC_ALL=C sort); then printf 'unexpected bare @Testcontainers annotation(s):\n' >&2 printf ' %s\n' "${bare_annotations[@]}" >&2 exit 1 From 5b70d6b12215db7a35f71e5f2fe53b95cd36f13c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:15:51 +1300 Subject: [PATCH 07/66] Order canonical JOIN candidates after the billing parent --- .../player-access-and-session.md | 4 +- ..._join_failure_and_attempt_diagnostics.sql} | 0 ...cal_join_existing_membership_terminal.sql} | 0 ...alJoinScopePersistenceIntegrationTest.java | 215 ++++++++++++++++++ 4 files changed, 218 insertions(+), 1 deletion(-) rename services/account-service/src/main/resources/db/migration/{V1035__canonical_join_failure_and_attempt_diagnostics.sql => V1037__canonical_join_failure_and_attempt_diagnostics.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V1037__canonical_join_existing_membership_terminal.sql => V1038__canonical_join_existing_membership_terminal.sql} (100%) 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 9c7585f298..afe8c0c036 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -20,10 +20,12 @@ The published foundation carrier #3389 deliberately leaves public facade and num ### Canonical public Account facade receiving -The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1035 diagnostics and V1037 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). +The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). Preserved source proof310 passes575selected Account units,318passes312facade units and two actual HTTP→Entity compositions,320passes42App PostgreSQL cases,321passes13first-JOIN cases,324passes22PLAYER_ADMISSION owner plus five shared cases, and335passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving343/345 establish793unique selected unit passes after correcting one obsolete first-only generic proof assertion;351passes169selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main198/200 holds remain. Remaining347static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused352transport proof passes all34mTLS client cases (31new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. Published #3390 carries this public source; the terminal-cancellation finding is independently qualified by the coupled356composition in #3389. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. +Receiving migration-order proof allocates the child-only JOIN diagnostics and existing-membership terminal guard as V1037/V1038 after the actual parent frontier V1036, retaining their SQL bytes and every applied-parent artifact. Proof430 supplies 28 passing canonical scope, first-JOIN and paid-JOIN PostgreSQL cases; its new upgrade case initially failed an incorrect shared-Saga expectation. Corrected proof432 passes the actual parent-history upgrade with unchanged canonical scope/PENDING-intent JSON and row `xmin`, complete prior Flyway rows/checksums, ordered installation of both scripts, a real attempt-diagnostics update and exact SQLSTATE `23514` immutable-caller refusal. Version checking428 and Account generation429 pass;432 also passes enabled integration analysis, formatting and documentation. The failed430 and no-matching-selector431 results remain retained rather than counted as successful aggregate proof. Account has no Common Saga runtime dependency at this boundary; declaring an optional classpath location does not supply those migration resources. + Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. The complete public WORLDS collection now accepts both canonical `SHARED` creation policies, `PRESEEDED_ONLY` and `PLAYER_CREATED`, without filtering a represented world or changing the one-public-target-per-tenant authority. Unknown/private policies, duplicate identities, changed collections and expired entitlement still refuse. The separate policy-specific source, roster and admission methods keep their own restrictions. This closes the accepted CLI1 discovery observation routed from #3383 in the existing public facade receiver. Proof379 passes all 341 focused cases with zero failures/errors/skips: the full 296-case Common Security suite, 33 Game Session collection/source cases and 12 Account WORLDS cases, including complete mixed-policy readback and deterministic entitlement filtering. Enabled affected analysis, formatting and docs pass. These are controlled component proofs, not successful public runtime or registration/custody qualification. diff --git a/services/account-service/src/main/resources/db/migration/V1035__canonical_join_failure_and_attempt_diagnostics.sql b/services/account-service/src/main/resources/db/migration/V1037__canonical_join_failure_and_attempt_diagnostics.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V1035__canonical_join_failure_and_attempt_diagnostics.sql rename to services/account-service/src/main/resources/db/migration/V1037__canonical_join_failure_and_attempt_diagnostics.sql diff --git a/services/account-service/src/main/resources/db/migration/V1037__canonical_join_existing_membership_terminal.sql b/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V1037__canonical_join_existing_membership_terminal.sql rename to services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index a34cacc9ab..9faf1e3893 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.mock; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -24,6 +25,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -281,6 +283,188 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE .isZero(); } + @Test + void receivingUpgradeFromParent1036PreservesCanonicalRowsAndHistory() { + String schema = createSchema("canonical_join_scope_"); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway parent = accountFlyway(dataSource, schema, "1036"); + parent.migrate(); + parent.validate(); + assertThat(parent.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1036")); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + Record account = + setupDsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING id, account_uuid", + "canonical-migration-upgrade-account", + "canonical-migration-upgrade@example.test", + "test-hash"); + long privateAccountId = Objects.requireNonNull(account).get("id", Long.class); + UUID accountUuid = Objects.requireNonNull(account).get("account_uuid", UUID.class); + + FreshTenantIdentityAssociationRepository freshTenants = + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod"); + FreshTenantCreationEvidence tenantSource = freshTenantEvidence(); + transaction.executeWithoutResult(status -> freshTenants.importVerified(tenantSource)); + AccountConnectScopeRepository scopes = + new AccountConnectScopeRepository( + transactionDsl, mock(AccountTenantIdentityResolver.class), freshTenants); + AccountJoinOperationRepository operations = + new AccountJoinOperationRepository(transactionDsl, scopes); + CanonicalJoinScopeV2 scope = canonicalScope(accountUuid, tenantSource.canonicalTenantId()); + VerifiedTenantProvenance tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantSource.operationId(), + tenantSource.evidenceDigest()); + String requestId = "canonical-migration-upgrade-pending"; + String callerBinding = "canonical-migration-upgrade-caller"; + transaction.executeWithoutResult( + status -> { + scopes.insertCanonical(privateAccountId, scope, tenantProvenance); + assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isTrue(); + }); + CanonicalJoinOperationEvidence pending = + transaction.execute( + status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow()); + assertThat(pending.status()).isEqualTo("PENDING"); + + String scopeTokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); + RetainedPhysicalRow retainedScope = + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(scope_row)::text, scope_row.xmin::text " + + "FROM account_connect_scope_records scope_row WHERE scope_token_hash = ?", + scopeTokenHash); + RetainedPhysicalRow retainedIntent = + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId); + List> parentHistory = flywayHistory(setupDsl); + assertThat(parentHistory) + .extracting(row -> row.get("script")) + .contains("V1036__hosting_subscription_terminal_resolution.sql") + .doesNotContain( + "V1037__canonical_join_failure_and_attempt_diagnostics.sql", + "V1038__canonical_join_existing_membership_terminal.sql"); + + Flyway current = accountFlyway(dataSource, schema, null); + current.migrate(); + current.validate(); + assertThat(current.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1038")); + + List> upgradedHistory = flywayHistory(setupDsl); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 2); + assertThat(upgradedHistory.subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + List> addedHistory = + upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); + assertThat(addedHistory).extracting(row -> row.get("version")).containsExactly("1037", "1038"); + assertThat(addedHistory) + .extracting(row -> row.get("script")) + .containsExactly( + "V1037__canonical_join_failure_and_attempt_diagnostics.sql", + "V1038__canonical_join_existing_membership_terminal.sql"); + assertThat(addedHistory) + .allSatisfy( + row -> { + assertThat(row.get("checksum")).isNotNull(); + assertThat(row.get("success")).isEqualTo(true); + }); + assertThat( + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(scope_row)::text, scope_row.xmin::text " + + "FROM account_connect_scope_records scope_row WHERE scope_token_hash = ?", + scopeTokenHash)) + .isEqualTo(retainedScope); + assertThat( + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId)) + .isEqualTo(retainedIntent); + + List installedConstraints = + setupDsl + .fetch( + "SELECT constraint_row.conname FROM pg_constraint constraint_row " + + "JOIN pg_class table_row ON table_row.oid = constraint_row.conrelid " + + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " + + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " + + "AND constraint_row.contype = 'c' AND constraint_row.convalidated", + schema) + .getValues(0, String.class); + assertThat(installedConstraints) + .contains( + "account_join_v2_attempt_diagnostics_check", + "account_join_exact_first_transition_check", + "account_join_operation_representation_check", + "account_join_canonical_terminal_proof_check"); + assertThat( + Objects.requireNonNull( + setupDsl.fetchOne( + "SELECT count(*) FROM pg_trigger trigger_row " + + "JOIN pg_class table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " + + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " + + "AND trigger_row.tgname = 'account_join_operation_identity_guard' " + + "AND trigger_row.tgenabled = 'O' AND NOT trigger_row.tgisinternal", + schema)) + .get(0, Long.class)) + .isEqualTo(1L); + String guardDefinition = + Objects.requireNonNull( + setupDsl.fetchOne( + "SELECT pg_get_functiondef(?::regprocedure)", + schema + ".guard_account_join_operation_identity()")) + .get(0, String.class); + assertThat(guardDefinition) + .contains("ALREADY_ACTIVE", "account_tenant_membership", "last_attempt_failure_code"); + + CanonicalJoinOperationEvidence diagnosed = + transaction.execute( + status -> + operations.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, "NOT_EVALUATED", "AUTH_UNAVAILABLE")); + assertThat(diagnosed.status()).isEqualTo("PENDING"); + assertThat(diagnosed.lastAttemptAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); + assertThat(diagnosed.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); + RetainedPhysicalRow diagnosedIntent = + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId); + assertThatThrownBy( + () -> + setupDsl.execute( + "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id = ?", + "changed-migration-caller", + requestId)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat( + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId)) + .isEqualTo(diagnosedIntent); + } + @Test void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { String schema = createSchema("canonical_scope_cleanup_"); @@ -801,6 +985,37 @@ private void assertNoSuccessEffects() { } } + private static Flyway accountFlyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + if (targetVersion != null) { + configuration.target(MigrationVersion.fromVersion(targetVersion)); + } + return configuration.load(); + } + + private static List> flywayHistory(DSLContext dsl) { + return dsl.fetch( + "SELECT installed_rank, version, description, type, script, checksum, installed_by, " + + "installed_on, execution_time, success FROM flyway_schema_history " + + "ORDER BY installed_rank") + .intoMaps(); + } + + private static RetainedPhysicalRow retainedPhysicalRow( + DSLContext dsl, String query, Object... bindings) { + Record row = Objects.requireNonNull(dsl.fetchOne(query, bindings)); + return new RetainedPhysicalRow(row.get(0, String.class), row.get(1, String.class)); + } + + private record RetainedPhysicalRow(String rowJson, String xmin) {} + private static long scopeRowCount(DSLContext dsl, String connectScopeId) { return Objects.requireNonNull( dsl.fetchOne( From 387afd65e1d398c2667c5f89e378febbaddeb111 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:21:54 +1300 Subject: [PATCH 08/66] Qualify public facade CI fixtures after catalog carry --- .../player-access-and-session.md | 4 +++- .../service/impl/AccountServiceImplTest.java | 3 ++- .../bootstrap/AccountBootstrapRosterFixture.java | 11 ++++++++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index afe8c0c036..8ef781d2ac 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -26,7 +26,9 @@ Preserved source proof310 passes575selected Account units,318passes312facade uni Receiving migration-order proof allocates the child-only JOIN diagnostics and existing-membership terminal guard as V1037/V1038 after the actual parent frontier V1036, retaining their SQL bytes and every applied-parent artifact. Proof430 supplies 28 passing canonical scope, first-JOIN and paid-JOIN PostgreSQL cases; its new upgrade case initially failed an incorrect shared-Saga expectation. Corrected proof432 passes the actual parent-history upgrade with unchanged canonical scope/PENDING-intent JSON and row `xmin`, complete prior Flyway rows/checksums, ordered installation of both scripts, a real attempt-diagnostics update and exact SQLSTATE `23514` immutable-caller refusal. Version checking428 and Account generation429 pass;432 also passes enabled integration analysis, formatting and documentation. The failed430 and no-matching-selector431 results remain retained rather than counted as successful aggregate proof. Account has no Common Saga runtime dependency at this boundary; declaring an optional classpath location does not supply those migration resources. -Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. +The original #3390 validation run `41692144820` exposed an obsolete entitlement-call expectation and an Entity test-fixture SpotBugs warning. Every discovery call joins all independent tenant reads, including failed calls, so the three-call fixture now expects three reads of each tenant. The fixture's generated protobuf request is immutable; narrow accessor/constructor annotations follow the existing fixture convention without changing detector configuration. Receiving proof443 passes all 312 Account facade cases, the physical allocate→later-prepare→selection regression on the carried V1059 schema, enabled Account test and Entity fixture analysis, formatting and documentation (1m38). Both original CI failures remain retained; replacement comparison CI is still required. + +Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The later exact `58a8a10` runtime-image run `41690067116` likewise fails PLAY because Account canonical tenant entitlement authority is unavailable; authenticated cleanup succeeds. Neither metadata-gate success nor local component proof replaces this failed runtime evidence. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. The complete public WORLDS collection now accepts both canonical `SHARED` creation policies, `PRESEEDED_ONLY` and `PLAYER_CREATED`, without filtering a represented world or changing the one-public-target-per-tenant authority. Unknown/private policies, duplicate identities, changed collections and expired entitlement still refuse. The separate policy-specific source, roster and admission methods keep their own restrictions. This closes the accepted CLI1 discovery observation routed from #3383 in the existing public facade receiver. Proof379 passes all 341 focused cases with zero failures/errors/skips: the full 296-case Common Security suite, 33 Game Session collection/source cases and 12 Account WORLDS cases, including complete mixed-policy readback and deterministic entitlement filtering. Enabled affected analysis, formatting and docs pass. These are controlled component proofs, not successful public runtime or registration/custody qualification. 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 40bf244b69..213eff2330 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 @@ -3444,7 +3444,8 @@ void listBootstrapWorldsFiltersGameplayUnavailableTenantAndFailsWhenEntitlementI assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(3)) .evaluate(demoTenant); - org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) + // Every discovery call joins all independent tenant reads, including a failed call. + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(3)) .evaluate(sandboxTenant); } diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java index 20081e085b..febbbd1d8d 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.entitymanagement.bootstrap; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -36,10 +37,18 @@ public final class AccountBootstrapRosterFixture { private AccountBootstrapRosterFixture() {} + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The retained generated protobuf request message is immutable.") public record Fixture( AccountBootstrapRosterReadRequest request, CanonicalGameplayRosterTarget target, - CanonicalGameplayRosterOwnerReadEvidence evidence) {} + CanonicalGameplayRosterOwnerReadEvidence evidence) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The retained generated protobuf request message is immutable.") + public Fixture {} + } public static Fixture create() throws Exception { var account = AuthoringFixtures.freshGraphRequest().accountBinding(); From 26d0b7a9de00afe7b4afe0991a3bec52db2fbd09 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 04:14:26 +1300 Subject: [PATCH 09/66] test: compose canonical player admission with committed login --- .../player-access-and-session.md | 6 + ...CurrentSourcesPostgresIntegrationTest.java | 100 ++++- ...mittedLoginCompositionIntegrationTest.java | 344 ++++++++++++++++++ ...titlementOwnerPostgresIntegrationTest.java | 136 ++++++- 4 files changed, 581 insertions(+), 5 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8ef781d2ac..b9ad4d802d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,12 @@ This is a non-normative implementation tracker for player access and session. Ca Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. +### Controlled player-admission transport composition + +The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. + +A further prepared [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java) replaces the LOGIN caller/currentness doubles with real committed issuance, response recovery, signature/profile verification and current Account owner reads. It uses a current persisted connect scope and physical Redis/PostgreSQL fixtures before calling the same unregistered mTLS receiver and Game Session consumer. Test signing custody, initial response delivery and protected published Game Session/World inputs remain controlled. The additional case also refuses a real Account token-fence revocation despite retained signature bytes and local custody. Compilation, enabled integration Checkstyle/SpotBugs, formatting and documentation checks pass. All five selected PostgreSQL cases, including this additional case, are skipped locally because Docker is unavailable; physical execution remains pending. No default PLAY route or activation is enabled. + ### Canonical billing and retention receiving The receiving foundation retains numeric subscription rows in the original renamed heap as immutable, non-authorizing evidence (V1028), installs canonical UUID subscription intent/provider history (V1029), and retains complete provisioning/lifecycle schema (V1030), first-dispatch claims (V1032) and cancellation-resolution journals (V1036). Retained history remains useful only for conservative deletion blockers; it is never current entitlement authority. The manually composed provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation prepares one allowed safe outcome. Coupled356physical proof now passes through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit. Its five PostgreSQL/AOF-replica cases cover atomic row/CAS/journal/receipt/audit/billing/tenant-event completion, canonical canceled current-read recovery, immutable failed history, authenticated replay, wrong credentials, late SQL rollback with restored OTP, authority change during the SDK read, and another Account's credential refusal. Enabled integration/test-fixture analysis and formatting pass. Unchanged355regression passes20lifecycle and21original-order cases; its original aggregate retains the corrected error-code expectation failure. These qualify the prepared cancellation component, with controlled policy/signer and Stripe transport inputs, and do not establish production custody or runtime registration. Provider absence and transfer are separate outcomes; production/default registration remains held and is not a prerequisite to qualifying this unregistered component boundary. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index cd5a6a33dd..a36e2e21ba 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -1434,8 +1434,21 @@ Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exce return newFixture(redisClient, "latest"); } + Fixture newPlayerEntitlementFixture(AccountGameplayDelegationRedisClient redisClient) + throws Exception { + return newFixture(redisClient, "latest", true); + } + private Fixture newFixture( AccountGameplayDelegationRedisClient redisClient, String migrationTarget) throws Exception { + return newFixture(redisClient, migrationTarget, false); + } + + private Fixture newFixture( + AccountGameplayDelegationRedisClient redisClient, + String migrationTarget, + boolean currentScope) + throws Exception { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); if (schema.length() > 63) throw new IllegalStateException("Generated schema name is too long"); runOwnedSchemas.add(schema); @@ -1452,7 +1465,8 @@ private Fixture newFixture( DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); - return new Fixture(schema, dataSource, dsl, manager, temporaryDirectory, redisClient); + return new Fixture( + schema, dataSource, dsl, manager, temporaryDirectory, redisClient, currentScope); } private static int awaitBackendBlockedBy( @@ -2041,7 +2055,8 @@ private Fixture( DSLContext dsl, DataSourceTransactionManager manager, Path temporaryDirectory, - AccountGameplayDelegationRedisClient redisClient) + AccountGameplayDelegationRedisClient redisClient, + boolean currentScope) throws Exception { this.schema = schema; this.dataSource = dataSource; @@ -2111,7 +2126,31 @@ private Fixture( newAccount.setPasswordHash("integration-fixture-password-hash"); newAccount.setRole("player"); this.account = transaction.execute(status -> accounts.save(newAccount)); - this.joinScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); + var retainedScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); + this.joinScope = + currentScope + ? new CanonicalJoinScopeV2( + retainedScope.connectScopeId(), + retainedScope.accountId(), + retainedScope.tenantId(), + retainedScope.realmId(), + retainedScope.tenantSlug(), + retainedScope.worldSlug(), + retainedScope.realmSlug(), + retainedScope.playableStateNamespaceId(), + retainedScope.playableStateScope(), + retainedScope.gameInstanceId(), + retainedScope.catalogRevision(), + retainedScope.pointerVersion(), + Instant.now() + .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) + .minusSeconds(5) + .toString(), + Instant.now() + .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) + .plusSeconds(120) + .toString()) + : retainedScope; establishTenantEntitlementAndMembership(connectScopes); AccountAuthEvidenceBundleRepository bundles = @@ -2125,6 +2164,61 @@ private Fixture( this.committedCandidate = createCommittedIssuanceCandidate(bundles, redisClient); } + CanonicalJoinScopeV2 playerEntitlementScope() { + return joinScope; + } + + void beginPlayerEntitlementLoginRevocation() { + var identity = tokenIdentity(committedCandidate); + UUID requestId = UUID.randomUUID(); + transaction.execute( + status -> + tokenFences.beginRevocationIntent( + identity, + requestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, requestId))); + } + + net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner + playerEntitlementOwner(CanonicalGameplayAdmissionDecisionReadClient protectedTargets) { + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), TEST_NAMESPACE), + freshTenants); + var snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sourceEvidence, + tenantAuthorityEvents, + freshTenants, + memberships, + membershipPairs, + membershipRoles, + authorityOutbox); + return new net.firedevops.firemud.accountservice.service + .AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + new AccountGameplayAdmissionCallerVerifier( + signerFixture.trustedJwksSource(), committedIssuanceOwner, Clock.systemUTC()), + issuance, + snapshots, + scopes, + mock(AccountHostingSubscriptionLifecycleRepository.class), + mock( + net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.class), + demoEntitlements, + tenantAuthorityEvents, + protectedTargets, + manager, + Clock.systemUTC(), + TEST_NAMESPACE); + } + private void establishTenantEntitlementAndMembership( AccountConnectScopeRepository connectScopes) { transaction.execute( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java new file mode 100644 index 0000000000..b7fec29bc4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java @@ -0,0 +1,344 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Server; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual committed LOGIN recovery/currentness, PostgreSQL DEMO and membership owners, Account + * receiver and Game Session consumer. Test signer/JWKS custody, initial response delivery and + * protected published Game Session/World inputs remain controlled. This does not prove public + * ingress, the default PLAY route, production custody, admission or activation. + */ +class AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String PEER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final Clock CLOCK = Clock.systemUTC(); + private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtures = + new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); + @TempDir Path directory; + + @BeforeAll + static void startPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); + } + + @AfterAll + static void stopPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); + } + + @AfterEach + void dropSchemas() { + fixtures.dropRunOwnedSchemas(); + } + + @Test + void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Exception { + fixtures.temporaryDirectory = directory; + var pki = + LoopbackMtlsTestPki.create( + directory, + "Actual LOGIN player entitlement composition", + new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/test/sa/account-service", true)); + try (var redis = + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture + .start()) { + var f = fixtures.newPlayerEntitlementFixture(redis.client()); + var identity = f.committedCandidate.identity(); + var initial = + InitialGameplayLoginResult.fromRecoveredCredential( + f.responseRecoveryOwner.recoverInitialLoginResponse( + identity.requestId(), + identity.accountId(), + new CallerIdentity(identity.callerWorkload(), identity.callerContextId()))); + var trusted = f.signerFixture.trustedJwksSource(); + var jwks = + new AccountPublicJwksCache( + trusted, trusted.sourceIdentity(), CLOCK, Duration.ofSeconds(30)); + var request = + AuthenticateRequest.newBuilder() + .setRequestId(initial.requestId().toString()) + .setEmail("controlled-delivery@example.test") + .setPassword("controlled-input") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(initial.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + try (var login = + CanonicalGameplayLoginResult.fromAuthenticatedResponse( + projectRecoveredInitial(initial), + request, + new AccountAsymmetricJwtVerifier(jwks, CLOCK), + CLOCK)) { + var scope = f.playerEntitlementScope(); + var protectedTargets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + controlledTarget(protectedTargets); + var owner = f.playerEntitlementOwner(protectedTargets); + var selector = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + scope.accountId(), + NAMESPACE, + scope.tenantId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + var ownerRequest = + new net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner + .Request(selector, scope.connectScopeId(), PEER); + byte[] compact = login.compactJwtBytes(); + net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + expected; + try { + expected = owner.evaluate(ownerRequest, new String(compact, StandardCharsets.US_ASCII)); + } finally { + Arrays.fill(compact, (byte) 0); + } + var targetFields = (Map) expected.fields().get("target"); + var sources = (Map) expected.fields().get("sourceReferences"); + var target = mock(CanonicalPlayableTarget.class); + when(target.targetNamespace()).thenReturn(NAMESPACE); + when(target.canonicalTenantId()).thenReturn(scope.tenantId()); + when(target.tenantSlug()).thenReturn(scope.tenantSlug()); + when(target.worldSlug()).thenReturn(scope.worldSlug()); + when(target.realmId()).thenReturn(scope.realmId()); + when(target.realmSlug()).thenReturn(scope.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(scope.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(scope.playableStateScope()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.canonicalGameInstanceId()).thenReturn(scope.gameInstanceId()); + when(target.canonicalVersionId()) + .thenReturn(UUID.fromString((String) targetFields.get("canonicalVersionId"))); + when(target.catalogRevision()).thenReturn(scope.catalogRevision()); + when(target.pointerVersion()).thenReturn(scope.pointerVersion()); + when(target.activeWorldEpoch()) + .thenReturn(Long.parseLong((String) targetFields.get("activeWorldEpoch"))); + when(target.admissionPointerSnapshotDigest()) + .thenReturn((String) sources.get("admissionPointerSnapshotDigest")); + when(target.ownerProofDigest()) + .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); + var claims = mock(ContextClaims.class); + when(claims.expiresAtMillis()) + .thenReturn(Instant.parse(scope.connectScopeExpiresAt()).toEpochMilli()); + var context = mock(FirstPartyConnectContext.class); + when(context.hasCompleteRoutingScope()).thenReturn(true); + when(context.claims()).thenReturn(claims); + when(context.accountId()).thenReturn(scope.accountId().toString()); + when(context.connectScopeId()).thenReturn(scope.connectScopeId()); + when(context.resolvedTarget()).thenReturn(target); + Server server = + new AccountPlayerAdmissionEntitlementGrpcService(owner, NAMESPACE) + .createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()); + server.start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var client = + new AccountPlayerAdmissionEntitlementClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + CLOCK)) { + client.init(); + var result = client.read(context, selector.readRequestId(), login, () -> true); + assertThat(result.fields()) + .containsEntry("variant", "PLAYER_ADMISSION") + .containsEntry("sourceKind", "NON_PAID_DEMO"); + assertThat(result.membershipSource().membershipExists()).isTrue(); + assertThat(result.membershipSource().gameplayAdmissionAllowed()).isTrue(); + var receivedSources = (Map) result.fields().get("sourceReferences"); + assertThat(receivedSources.get("callerTokenSha256")).isEqualTo(initial.tokenSha256()); + assertThat(receivedSources.get("callerTokenJti")) + .isEqualTo(initial.tokenJti().toString()); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) + .isInstanceOf(RuntimeException.class); + // Retaining valid signature bytes and local custody is insufficient after Account moves. + f.beginPlayerEntitlementLoginRevocation(); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) + .isInstanceOf(RuntimeException.class); + login.close(); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) + .isInstanceOf(RuntimeException.class); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ + private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { + when(targets.resolvePublishedRealmAdmissionTarget(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + .class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer( + readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return read; + }); + return resolved; + }); + } + + private static AuthenticateResponse projectRecoveredInitial(InitialGameplayLoginResult result) { + byte[] token = result.compactJwtBytes(); + try { + return AuthenticateResponse.newBuilder() + .setAuthToken(new String(token, StandardCharsets.US_ASCII)) + .setAccountId(result.accountId().toString()) + .setRequestId(result.requestId().toString()) + .setCallerContextId(result.callerContextId().toString()) + .setTokenJti(result.tokenJti().toString()) + .setTokenSha256(result.tokenSha256()) + .setTokenProfile(result.profile()) + .setIssuedAtEpochSeconds(result.issuedAtEpochSecond()) + .setNotBeforeEpochSeconds(result.notBeforeEpochSecond()) + .setExpiresAtEpochSeconds(result.expiresAtEpochSecond()) + .setTokenGeneration(result.tokenGeneration()) + .setIssuanceFence(result.issuanceFence()) + .setAuthorityTupleCanonicalJson(ByteString.copyFrom(result.authorityTupleCanonicalJson())) + .setOutboxCheckpointsCanonicalJson( + ByteString.copyFrom(result.outboxCheckpointsCanonicalJson())) + .setOutboxSourceEventEvidenceCanonicalJson( + ByteString.copyFrom(result.outboxSourceEventEvidenceCanonicalJson())) + .build(); + } finally { + Arrays.fill(token, (byte) 0); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 57cd9d560a..e71847e560 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -8,17 +8,23 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; import java.sql.Connection; import java.sql.SQLException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.HexFormat; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; @@ -50,17 +56,27 @@ import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -69,6 +85,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -81,7 +98,9 @@ * Physical canonical Account/membership/scope/demo composition and lock/commit proof definitions. * JWT/JWKS/Redis caller verification and current committed issuance are controlled doubles here; * the protected GS/World client is also controlled. This does not prove custody, actual issuance, - * paid composition, mTLS or physical published routing. + * paid composition or physical published routing. The explicit loopback composition additionally + * uses the actual Account receiver and Game Session client over mTLS; its LOGIN and target inputs + * remain controlled doubles, not genuine custody or production activation. */ class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { private static final String SCHEMA_PREFIX = "player_entitlement_"; @@ -92,6 +111,7 @@ class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); private static final AccountPostgresIntegrationFixture POSTGRES = new AccountPostgresIntegrationFixture(); + @TempDir Path certificateDirectory; private final Set schemas = ConcurrentHashMap.newKeySet(); @BeforeAll @@ -116,6 +136,118 @@ void dropOwnedSchemas() { schemas.clear(); } + @Test + void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission() + throws Exception { + var pki = + LoopbackMtlsTestPki.create( + certificateDirectory, + "Controlled player admission composition", + new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true)); + for (boolean joined : new boolean[] {false, true}) { + Fixture f = fixture(joined); + var request = f.request(); + var expected = f.owner.evaluate(request, "controlled-token"); + var targetFields = (Map) expected.fields().get("target"); + var sources = (Map) expected.fields().get("sourceReferences"); + // Only the upstream target/custody are doubles. No owner, receiver or consumer is mocked. + var target = mock(CanonicalPlayableTarget.class); + when(target.targetNamespace()).thenReturn(NAMESPACE); + when(target.canonicalTenantId()).thenReturn(f.tenantId); + when(target.tenantSlug()).thenReturn(f.scope.tenantSlug()); + when(target.worldSlug()).thenReturn(f.scope.worldSlug()); + when(target.realmId()).thenReturn(f.scope.realmId()); + when(target.realmSlug()).thenReturn(f.scope.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(f.scope.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn("SHARED"); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.canonicalGameInstanceId()).thenReturn(f.scope.gameInstanceId()); + when(target.canonicalVersionId()) + .thenReturn(UUID.fromString((String) targetFields.get("canonicalVersionId"))); + when(target.catalogRevision()).thenReturn(f.scope.catalogRevision()); + when(target.pointerVersion()).thenReturn(f.scope.pointerVersion()); + when(target.activeWorldEpoch()) + .thenReturn(Long.parseLong((String) targetFields.get("activeWorldEpoch"))); + when(target.admissionPointerSnapshotDigest()) + .thenReturn((String) sources.get("admissionPointerSnapshotDigest")); + when(target.ownerProofDigest()) + .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); + var claims = mock(ContextClaims.class); + when(claims.expiresAtMillis()).thenReturn(NOW.plusSeconds(120).toEpochMilli()); + var context = mock(FirstPartyConnectContext.class); + when(context.hasCompleteRoutingScope()).thenReturn(true); + when(context.claims()).thenReturn(claims); + when(context.accountId()).thenReturn(f.account.getAccountUuid().toString()); + when(context.connectScopeId()).thenReturn(f.scope.connectScopeId()); + when(context.resolvedTarget()).thenReturn(target); + var login = mock(CanonicalGameplayLoginResult.class); + when(login.compactJwtBytes()) + .thenAnswer(invocation -> "controlled-token".getBytes(StandardCharsets.US_ASCII)); + when(login.evidence()) + .thenReturn( + new CanonicalGameplayLoginResult.NonSecretEvidence( + f.account.getAccountUuid(), + UUID.randomUUID(), + UUID.fromString((String) sources.get("callerContextId")), + UUID.fromString((String) sources.get("callerTokenJti")), + controlledTokenDigest(), + GameSessionAccountDelegationProfile.PROFILE, + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + "1", + "1", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY)); + var receiver = new AccountPlayerAdmissionEntitlementGrpcService(f.owner, NAMESPACE); + var server = + receiver.createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()); + server.start(); + long membershipsBefore = f.dsl.fetchCount(DSL.table("account_tenant_membership")); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var client = + new AccountPlayerAdmissionEntitlementClient( + endpoints, + pki.clientProperties(certificateDirectory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + Clock.fixed(NOW, ZoneOffset.UTC))) { + client.init(); + var received = client.read(context, request.requestId(), login, () -> true); + assertThat(received.canonicalBytes()).isEqualTo(expected.canonicalBytes()); + assertThat(received.membershipSource().membershipExists()).isEqualTo(joined); + assertThat(received.membershipSource().gameplayAdmissionAllowed()).isEqualTo(joined); + assertThat(new String(received.canonicalBytes(), StandardCharsets.UTF_8)) + .doesNotContain("controlled-token"); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) + .isInstanceOf(RuntimeException.class); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))) + .isEqualTo(membershipsBefore); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static String controlledTokenDigest() { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest("controlled-token".getBytes(StandardCharsets.US_ASCII))); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + @Test void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { Fixture f = fixture(false); @@ -491,7 +623,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); when(candidate.signerCorrespondence()) .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); - when(candidate.tokenSha256()).thenReturn("a".repeat(64)); + when(candidate.tokenSha256()).thenReturn(controlledTokenDigest()); when(candidate.signerKid()).thenReturn("controlled-kid"); when(candidate.signerGeneration()).thenReturn("1"); when(candidate.canonicalRegistryRecordSha256()).thenReturn("b".repeat(64)); From 4a0f1e0c04569e70cc0a40c673a42da98017c2e0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 05:11:54 +1300 Subject: [PATCH 10/66] test: compose actual published admission sources and correct controlled token syntax --- ...titlementOwnerPostgresIntegrationTest.java | 20 +- .../game-session-service/build.gradle.kts | 1 + ...dmissionActualOwnerCompositionFixture.java | 51 ++++ ...ationOwnerCompositionCrossServiceTest.java | 7 + ...ldPublishedAdmissionSourceComposition.java | 231 ++++++++++++++++++ 5 files changed, 301 insertions(+), 9 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java create mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index e71847e560..c94ecd8279 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -104,6 +104,8 @@ */ class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { private static final String SCHEMA_PREFIX = "player_entitlement_"; + // Syntax-only credential for the explicitly mocked caller verifier, not a signed LOGIN. + private static final String CONTROLLED_COMPACT_TOKEN = "e30.e30.c2lnbmF0dXJl"; private static final String NAMESPACE = "player-entitlement-proof"; private static final String ISSUER = "firemud-account-service"; private static final String PEER = @@ -149,7 +151,7 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( for (boolean joined : new boolean[] {false, true}) { Fixture f = fixture(joined); var request = f.request(); - var expected = f.owner.evaluate(request, "controlled-token"); + var expected = f.owner.evaluate(request, CONTROLLED_COMPACT_TOKEN); var targetFields = (Map) expected.fields().get("target"); var sources = (Map) expected.fields().get("sourceReferences"); // Only the upstream target/custody are doubles. No owner, receiver or consumer is mocked. @@ -184,7 +186,7 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( when(context.resolvedTarget()).thenReturn(target); var login = mock(CanonicalGameplayLoginResult.class); when(login.compactJwtBytes()) - .thenAnswer(invocation -> "controlled-token".getBytes(StandardCharsets.US_ASCII)); + .thenAnswer(invocation -> CONTROLLED_COMPACT_TOKEN.getBytes(StandardCharsets.US_ASCII)); when(login.evidence()) .thenReturn( new CanonicalGameplayLoginResult.NonSecretEvidence( @@ -225,7 +227,7 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( assertThat(received.membershipSource().membershipExists()).isEqualTo(joined); assertThat(received.membershipSource().gameplayAdmissionAllowed()).isEqualTo(joined); assertThat(new String(received.canonicalBytes(), StandardCharsets.UTF_8)) - .doesNotContain("controlled-token"); + .doesNotContain(CONTROLLED_COMPACT_TOKEN); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) .isInstanceOf(RuntimeException.class); assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))) @@ -242,7 +244,7 @@ private static String controlledTokenDigest() { return HexFormat.of() .formatHex( MessageDigest.getInstance("SHA-256") - .digest("controlled-token".getBytes(StandardCharsets.US_ASCII))); + .digest(CONTROLLED_COMPACT_TOKEN.getBytes(StandardCharsets.US_ASCII))); } catch (java.security.NoSuchAlgorithmException unavailable) { throw new IllegalStateException(unavailable); } @@ -252,7 +254,7 @@ private static String controlledTokenDigest() { void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { Fixture f = fixture(false); long before = f.dsl.fetchCount(DSL.table("account_tenant_membership")); - var value = f.owner.evaluate(f.request(), "controlled-token"); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); assertThat(value.membershipSource().accountId()) .isEqualTo(f.account.getAccountUuid().toString()); @@ -278,7 +280,7 @@ void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMember @Test void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { Fixture f = fixture(true); - var value = f.owner.evaluate(f.request(), "controlled-token"); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); assertThat(value.membershipSource().membershipExists()).isTrue(); assertThat(value.membershipSource().membershipVersion()) .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); @@ -291,7 +293,7 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { assertThat(binding.get("gameInstanceId")).isEqualTo(f.scope.gameInstanceId().toString()); assertThat(binding.get("catalogRevision")).isEqualTo("7"); assertThat(binding.get("pointerVersion")).isEqualTo("3"); - assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), "controlled-token"); + assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), CONTROLLED_COMPACT_TOKEN); } @Test @@ -333,7 +335,7 @@ public void beforeCommit(boolean readOnly) { }) .when(f.demos) .readCurrent(f.tenantId); - assertThatThrownBy(() -> f.owner.evaluate(f.request(), "controlled-token")) + assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) .hasMessageContaining("controlled final source commit refusal"); assertThat(competingWriterRefused.get()).isTrue(); var unlocked = @@ -633,7 +635,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { var caller = mock(VerifiedCaller.class); when(caller.identity()).thenReturn(identity); when(caller.currentCandidate()).thenReturn(candidate); - when(callers.verifyPresentedCompactToken("controlled-token")).thenReturn(caller); + when(callers.verifyPresentedCompactToken(CONTROLLED_COMPACT_TOKEN)).thenReturn(caller); when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) .thenAnswer( invocation -> { diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index ab2b77fa28..6478b840db 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -187,6 +187,7 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture*.class") } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java new file mode 100644 index 0000000000..7ec6ed0f27 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.grpc.BindableService; +import io.grpc.ServerInterceptors; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; +import org.jooq.DSLContext; + +/** + * Assembles actual current Game Session source readers over caller-owned PostgreSQL state. The + * caller owns source provenance, authenticated clients, socket identity and cleanup. This fixture + * creates no rows, changes no registration and does not authorize gameplay admission. + */ +public final class CanonicalPublishedAdmissionActualOwnerCompositionFixture { + private CanonicalPublishedAdmissionActualOwnerCompositionFixture() {} + + public static BindableService receiver( + DSLContext dsl, + String namespace, + GameDesignPublishedRealmPolicyClient policies, + WorldCanonicalInstanceLifecycleClient world) { + var catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); + var admissions = + new CanonicalInitialAdmissionRepository( + dsl, + catalogs, + new GameSessionCanonicalAdmissionPointerRepository( + dsl, catalogs, new GameplayAdmissionPointerEventRepository(dsl))); + var launches = new CanonicalGameInstanceLaunchAssociationRepository(dsl, namespace); + var routes = new CanonicalPlayerRouteReadService(namespace, catalogs, admissions, launches); + var published = + new CanonicalPublishedPlayerRouteReadService( + namespace, routes, catalogs, launches, policies); + var guard = new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(namespace); + var receiver = + new CanonicalGameplayAdmissionDecisionReadGrpcService( + new CanonicalGameplayBindingInventoryRepository(dsl), + guard, + namespace, + null, + routes, + published, + launches, + world); + return () -> ServerInterceptors.intercept(receiver, guard); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 448b954fd5..e7c312d99a 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -3436,6 +3436,13 @@ private static void composeActualEntityWorldRegionPrerequisite( try { var worldEndpoints = new ServiceEndpointsProperties(); worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); + WorldPublishedAdmissionSourceComposition.exercise( + proofDirectory, + gs.dsl(), + currentTarget, + accountUuid, + worldEndpoints, + worldPki.client("game-session-service")); var initialLocationClient = new CanonicalInitialPlayerLocationClient( worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java new file mode 100644 index 0000000000..2a9e92090d --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.BindableService; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalPublishedAdmissionActualOwnerCompositionFixture; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Real GS OPEN/current publication reader and World ACTIVE owner over authenticated sockets. + * Upstream Game Design publication and ephemeral PKI remain controlled test inputs. This reads + * evidence only, and does not establish LOGIN, entitlement, gameplay binding or activation. + */ +final class WorldPublishedAdmissionSourceComposition { + private WorldPublishedAdmissionSourceComposition() {} + + static void exercise( + Path root, + DSLContext gs, + CanonicalPlayableTarget target, + UUID account, + ServiceEndpointsProperties worldEndpoints, + CommonGrpcClientProperties worldTls) + throws Exception { + assertThat(target.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); + var publication = + RealmPolicyPublishedEvidenceCodec.decode( + gs.fetchSingle( + "SELECT complete_policy_set_evidence FROM game_session_canonical_realm_catalog WHERE realm_id=?", + target.realmId()) + .get(0, byte[].class)); + String namespace = target.targetNamespace(); + Path directory = Files.createDirectories(root.resolve("published-admission-source")); + var pki = + LoopbackMtlsTestPki.create( + directory, + "Controlled published source composition", + new LoopbackMtlsTestPki.IdentitySpec( + "gs-server", peer(namespace, "game-session-service"), true), + new LoopbackMtlsTestPki.IdentitySpec( + "gs-client", peer(namespace, "game-session-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", peer(namespace, "account-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "design", peer(namespace, "game-design-service"), true)); + var policies = + new PublishedRealmEntryPolicySetEvidence( + publication.target(), + publication.versionNumber(), + publication.sourceCommitId(), + publication.sourceEpoch(), + publication.publishedReleaseBundleRef(), + publication.publishedReleaseBundleDigest(), + publication.publishWorkflowId(), + publication.manifestHash(), + publication.publicationVersionStateEpoch(), + publication.operationBytes(), + publication.captureBytes(), + publication.terminalEvidenceBytes(), + publication.policyCount(), + publication.policySetDigest(), + publication.policies().stream() + .map( + p -> + new PublishedRealmEntryPolicyEvidence( + p.policyId(), + p.source().commitId(), + p.source().revisionId(), + p.source().logicalRevisionId(), + p.source().policy(), + p.policyDigest())) + .toList()); + // This is the sole stipulated source: the exact published set already used by the real + // preparation/OPEN owners. No Game Design issuing-owner proof is claimed here. + var policySource = + new PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase() { + @Override + public void listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest request, + StreamObserver observer) { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo(peer(namespace, "game-session-service")); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + observer.onNext( + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(request), policies)); + observer.onCompleted(); + } + }; + Server design = server(pki, "design", policySource); + try { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + design.getPort()); + var channels = new GrpcChannelFactory(); + try (var policyClient = + new GameDesignPublishedRealmPolicyClient( + endpoints, + pki.clientProperties(directory, pki.identity("gs-client")), + channels, + namespace); + var worldClient = + new WorldCanonicalInstanceLifecycleClient( + worldEndpoints, worldTls, channels, namespace)) { + policyClient.init(); + worldClient.init(); + Server receiver = + server( + pki, + "gs-server", + CanonicalPublishedAdmissionActualOwnerCompositionFixture.receiver( + gs, namespace, policyClient, worldClient)); + try { + endpoints.setGameSessionService("localhost:" + receiver.getPort()); + try (var accountClient = + new CanonicalGameplayAdmissionDecisionReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("account")), + channels, + namespace)) { + accountClient.init(); + var selector = + new RetainedTargetSelector( + UUID.randomUUID(), + account, + namespace, + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + var resolved = accountClient.resolvePublishedRealmAdmissionTarget(selector); + var read = accountClient.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + assertThat(read.selector()).isEqualTo(resolved.strictSelector()); + assertThat(read.currentTarget().canonicalGameInstanceId()) + .isEqualTo(target.canonicalGameInstanceId()); + assertThat(read.sourceEvidence().admissionPointerSnapshotDigest()) + .isEqualTo(target.admissionPointerSnapshotDigest()); + assertThat(read.sourceEvidence().gameSessionOwnerProof().proofDigest()) + .isEqualTo(target.ownerProofDigest()); + assertThat(read.sourceEvidence().publishedPolicySetEvidence().canonicalBytes()) + .containsExactly(policies.canonicalBytes()); + assertThat(read.worldLifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(read.worldLifecycleEvidence().lifecycleEpoch()) + .isEqualTo(target.activeWorldEpoch()); + var wrong = + new RetainedTargetSelector( + UUID.randomUUID(), + account, + namespace, + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + UUID.randomUUID(), + target.catalogRevision(), + target.pointerVersion()); + assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) + .isInstanceOf(RuntimeException.class); + } + } finally { + stop(receiver); + } + } + } finally { + stop(design); + } + } + + private static String peer(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static Server server( + LoopbackMtlsTestPki.Pki pki, String identity, BindableService receiver) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( + pki.keyManagerFactory(pki.identity(identity)))) + .trustManager(pki.trustManagerFactory()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } +} From 86165d67f2dfccd2e98424a945453d5292aa451f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 05:56:19 +1300 Subject: [PATCH 11/66] test: compose genuine login and joined player admission sources --- services/account-service/build.gradle.kts | 10 +- .../AccountControlUiOriginalOrderFixture.java | 76 ++- .../AccountControlUiOwnerSourcesFixture.java | 71 ++- ...ayerAdmissionSharedEntitlementFixture.java | 559 ++++++++++++++++++ ...ountPlayerAdmissionSharedOwnerFixture.java | 455 ++++++++++++++ ...ationOwnerCompositionCrossServiceTest.java | 56 +- ...PlayerAdmissionEntitlementComposition.java | 224 +++++++ ...ldPublishedAdmissionSourceComposition.java | 11 +- 8 files changed, 1427 insertions(+), 35 deletions(-) create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java create mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index d7d9bdbcfd..5b1ceb456f 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -185,7 +185,7 @@ tasks.named("integrationTest") { classpath = classpath.filter { it !in socialArtifacts } + files(extractSocialIntegrationTestClasses) } -// Owner proof exports classes and its required registry script without Account application or +// Owner proof exports classes and required registry/projection resources without Account application or // Flyway resources, so a receiving service retains its own configuration and migration ownership. val accountOriginalOrderProofJar by tasks.registering(Jar::class) { archiveClassifier.set("original-order-proof") @@ -194,6 +194,14 @@ val accountOriginalOrderProofJar by tasks.registering(Jar::class) { from(sourceSets["testFixtures"].output.classesDirs) from("src/main/resources") { include("redis/lua/account-control-ui-registry-cas.lua") + include("redis/lua/account-game-session-delegation-pending-register.lua") + include("redis/lua/account-game-session-delegation-activate-committed.lua") + include("redis/lua/account-game-session-delegation-authority-project.lua") + include("redis/account_generation_projection_cas.lua") + include("redis/scripts/account-game-session-delegation-pending-register.json") + include("redis/scripts/account-game-session-delegation-activate-committed.json") + include("redis/scripts/account-game-session-delegation-authority-project-issuer.json") + include("redis/scripts/account-generation-projection-cas.json") } } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 14e01a13bd..c08602aa0a 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -27,6 +27,7 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; /** * Genuine Account owner mutations. Fresh creator/legal sources and signer platform evidence are @@ -100,6 +101,35 @@ public AccountControlUiOriginalOrderFixture( ownedCompositionConnections); } + /** + * Test-only composition with one preselected Game Design provenance tuple shared by Account and + * World. It is imported during construction, never substituted onto existing associations. + */ + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + FreshTenantCreationEvidence creationEvidence, + boolean ownedCompositionConnections) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + Objects.requireNonNull(creationEvidence, "creationEvidence").canonicalTenantId(), + Clock.systemUTC(), + null, + Clock.systemUTC(), + ownedCompositionConnections, + creationEvidence); + } + /** Actor clock is injectable for genuine signed-credential expiry recovery proof. */ public AccountControlUiOriginalOrderFixture( String jdbcUrl, @@ -193,6 +223,35 @@ private AccountControlUiOriginalOrderFixture( Clock serviceClock, boolean ownedCompositionConnections) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + serviceClock, + ownedCompositionConnections, + AccountControlUiOwnerSourcesFixture.defaultCreation(gameDesignTenant)); + } + + private AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + Clock serviceClock, + boolean ownedCompositionConnections, + FreshTenantCreationEvidence creationEvidence) + throws Exception { this.temporary = temporary; Objects.requireNonNull(actorClock, "actorClock"); Objects.requireNonNull(serviceClock, "serviceClock"); @@ -205,7 +264,8 @@ private AccountControlUiOriginalOrderFixture( false, gameDesignTenant, migrationTarget, - ownedCompositionConnections); + ownedCompositionConnections, + creationEvidence); RedisClient allocatedClient = null; try { signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); @@ -235,6 +295,8 @@ private AccountControlUiOriginalOrderFixture( .on() .addPassword(PASSWORD) .keyPattern("session:auth:token:*") + .keyPattern("session:auth:generation:issuer:*") + .keyPattern("session:auth:generation:account:*") .addCommand(io.lettuce.core.protocol.CommandType.HELLO) .addCommand(io.lettuce.core.protocol.CommandType.PING) .addCommand( @@ -250,6 +312,8 @@ private AccountControlUiOriginalOrderFixture( .addCommand(io.lettuce.core.protocol.CommandType.GET) .addCommand(io.lettuce.core.protocol.CommandType.SET) .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.PTTL) + .addCommand(io.lettuce.core.protocol.CommandType.TYPE) .addCommand(io.lettuce.core.protocol.CommandType.TIME)); connection .sync() @@ -335,6 +399,16 @@ public UUID tenantId() { return f.tenant; } + /** The exact immutable source tuple imported at construction for cross-owner composition. */ + public FreshTenantCreationEvidence creationEvidence() { + return f.creationEvidence; + } + + /** Reuse the same physical test-only Account writer without resetting its ACL or credentials. */ + AccountCoordinationPinnedConnectionProvider gameplayConnectionProvider() { + return () -> accountClient.connect(ByteArrayCodec.INSTANCE); + } + /** * Real Account-owned selected Game Logic source reads over this fixture's SQL and Coordination * Redis owners; callers choose the clock and target namespace for their composition. diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 3f2a920a59..f6f082f13d 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -99,6 +99,7 @@ final class AccountControlUiOwnerSourcesFixture { final Account account; final AccountRepository accounts; final UUID tenant; + final FreshTenantCreationEvidence creationEvidence; final UUID request = UUID.randomUUID(), callerContext = UUID.randomUUID(); final AtomicReference boundary = new AtomicReference<>(testBoundary("test-production")); @@ -162,6 +163,35 @@ final class AccountControlUiOwnerSourcesFixture { String migrationTarget, boolean ownedCompositionConnections) throws Exception { + this( + jdbcUrl, + username, + password, + root, + installNegativeIssuer, + tenant, + migrationTarget, + ownedCompositionConnections, + defaultCreation(tenant)); + } + + /** Shared immutable provenance must be supplied before any Account association is created. */ + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant, + String migrationTarget, + boolean ownedCompositionConnections, + FreshTenantCreationEvidence creationEvidence) + throws Exception { + this.creationEvidence = Objects.requireNonNull(creationEvidence, "creationEvidence"); + if (!creationEvidence.canonicalTenantId().equals(tenant)) { + throw new IllegalArgumentException( + "Shared creation evidence must identify the Account tenant"); + } if (migrationTarget != null && !HISTORICAL_MIGRATION_TARGETS.contains(migrationTarget)) { throw new IllegalArgumentException( "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); @@ -207,8 +237,9 @@ final class AccountControlUiOwnerSourcesFixture { candidate.setLoginAuthModes("EMAIL_OTP"); return accounts.save(candidate); }); - var creator = testCreation(account.getAccountUuid(), tenant); - var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + var creator = testCreation(account.getAccountUuid(), creationEvidence); + var fresh = + new FreshTenantIdentityAssociationRepository(dsl, creationEvidence.targetNamespace()); tx( () -> { fresh.importVerified(creator.creationEvidence()); @@ -669,26 +700,28 @@ void assertNoIssuance() { assertThat(coordinationCalls).hasValue(0); } - private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { - UUID request = UUID.randomUUID(), - operation = UUID.randomUUID(), - authorization = UUID.randomUUID(); + static FreshTenantCreationEvidence defaultCreation(UUID tenant) { + UUID request = UUID.randomUUID(), operation = UUID.randomUUID(); String key = "test-only-game-row-17"; String digest = GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); - var creation = - new FreshTenantCreationEvidence( - 1, - NAMESPACE, - request, - operation, - digest, - tenant, - 17L, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + } + + private static FreshTenantCreatorEvidence testCreation( + UUID account, FreshTenantCreationEvidence creation) { + UUID authorization = UUID.randomUUID(); String authorizationDigest = "sha256:" + "8".repeat(64); return new FreshTenantCreatorEvidence( 1, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java new file mode 100644 index 0000000000..0040681212 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java @@ -0,0 +1,559 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner.RealmScope; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Separate global-player composition over the original Account database and real protected target + * client. Repository insertion, absence enrollment, DEMO provisioning, LOGIN/currentness, canonical + * scope production and the entitlement receiver use their actual owners. The player has no tenant + * membership, no roles and no admission permission until the explicit first-JOIN method runs; the + * original creator is never rewritten. + * + *

Construct only after the original creator/operator authoring sequence is finished: DEMO + * advances tenant authority, which deliberately makes the creator's historical baseline unsuitable + * for current runtime membership evidence. Scope peer/context custody, demo policy, enrollment/OTP + * delivery and test signing-key custody remain controlled. Paid and browser-only dependencies fail + * on every call and cannot supply successful evidence. This helper borrows connections, registers + * no runtime beans, opens no listener and claims no public ingress, World hold or PLAY authority. + * Its optional first JOIN proves only Account-local atomic membership/event/audit/receipt + * ownership. + */ +public final class AccountPlayerAdmissionSharedEntitlementFixture { + private static final SecureRandom RANDOM = new SecureRandom(); + private final AccountControlUiOwnerSourcesFixture sources; + private final AccountPlayerAdmissionSharedOwnerFixture login; + private final AccountCanonicalRuntimeMembershipSnapshotRepository snapshots; + private final AccountDemoTenantEntitlementRepository demos; + private final DemoTenantEntitlementSnapshot demo; + private final AccountCanonicalPublicRealmScopeOwner scopes; + private final AccountCanonicalConnectScopeReader scopeReader; + private final CanonicalGameplayAdmissionDecisionReadClient targets; + private final AccountAuthoritySourceEvidenceRepository authority; + private final AccountAuthorityOutboxRepository outbox; + private final AccountTenantMembershipRepository members; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountJoinOperationRepository operations; + private final AccountAuditOutboxRepository audits; + private final AccountCanonicalFirstJoinTerminalCoordinator firstJoin; + private final TransactionTemplate joinTransaction; + private final AccountPlayerAdmissionEntitlementGrpcService receiver; + private final AccountHostingSubscriptionLifecycleRepository unusedPaidRepository; + private final StripeHostingSubscriptionObserver unusedProvider; + private final SessionService unusedBrowserSessions; + private final Clock clock; + private final String namespace; + + public AccountPlayerAdmissionSharedEntitlementFixture( + AccountControlUiOriginalOrderFixture original, + Path temporary, + CanonicalGameplayAdmissionDecisionReadClient genuineTargets, + DemoTenantEntitlementRequest demoRequest) + throws Exception { + this(original, temporary, genuineTargets, demoRequest, Clock.systemUTC()); + } + + public AccountPlayerAdmissionSharedEntitlementFixture( + AccountControlUiOriginalOrderFixture original, + Path temporary, + CanonicalGameplayAdmissionDecisionReadClient genuineTargets, + DemoTenantEntitlementRequest demoRequest, + Clock clock) + throws Exception { + Objects.requireNonNull(original, "Original Account fixture is required"); + targets = + Objects.requireNonNull( + genuineTargets, "Actual initialized protected target client is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + FreshTenantCreationEvidence creation = original.creationEvidence(); + requireFirstDemoRequest(demoRequest, creation); + namespace = creation.targetNamespace(); + sources = original.preparedOriginalCreator().sources(); + login = AccountPlayerAdmissionSharedOwnerFixture.freshGlobalPlayer(original, temporary, clock); + + var generations = new AccountAuthorityGenerationRepository(sources.dsl); + outbox = new AccountAuthorityOutboxRepository(sources.dsl); + authority = new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); + var fresh = new FreshTenantIdentityAssociationRepository(sources.dsl, namespace); + pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); + members = new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(sources.dsl); + var billing = new AccountTenantEntitlementOutboxRepository(sources.dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(sources.dsl, outbox, billing, fresh, generations); + demos = + new AccountDemoTenantEntitlementRepository( + sources.dsl, fresh, generations, billing, tenantEvents); + snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + sources.accounts, + generations, + authority, + tenantEvents, + fresh, + members, + pairs, + roles, + outbox); + // Missing rows alone are not evidence. Enroll the exact account-fenced absence baseline. + demo = + sources.tx( + () -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + generations.initialize(AuthorityScope.membership(login.accountId(), sources.tenant)); + members.prepareFreshCreatorAbsence(login.accountId(), sources.tenant); + return demos.provision(demoRequest, creation); + }); + + var retainedScopes = + new AccountConnectScopeRepository( + sources.dsl, + new AccountTenantIdentityResolver( + new ApprovedLegacyTenantAssociationRepository( + sources.dsl, new LegacyTenantSourceEvidence(sources.dsl), namespace), + namespace), + fresh); + unusedPaidRepository = excluded(AccountHostingSubscriptionLifecycleRepository.class); + unusedProvider = excluded(StripeHostingSubscriptionObserver.class); + unusedBrowserSessions = excluded(SessionService.class); + var hosting = + new AccountHostingSubscriptionLifecycleService( + unusedPaidRepository, unusedProvider, sources.manager); + var publicEntitlements = + new AccountPublicBootstrapEntitlementOwner( + tenantEvents, hosting, demos, sources.manager, clock); + var tokens = new AccountTokenProperties(); + var jwt = new JwtUtil(scopeSigningKey(), tokens.getConnectScopeExpirationMs()); + scopeReader = + new AccountCanonicalConnectScopeReader(jwt, retainedScopes, sources.manager, clock); + operations = new AccountJoinOperationRepository(sources.dsl, retainedScopes); + audits = new AccountAuditOutboxRepository(sources.dsl); + var membershipEvents = + transactional( + new AccountMembershipAuthorityEventProducer( + operations, + sources.accounts, + pairs, + members, + roles, + generations, + outbox, + authority, + tenantEvents, + demos), + AccountMembershipAuthorityEventProducer.class); + firstJoin = + transactional( + new AccountCanonicalFirstJoinTerminalCoordinator( + sources.accounts, + operations, + members, + roles, + outbox, + pairs, + audits, + membershipEvents), + AccountCanonicalFirstJoinTerminalCoordinator.class); + joinTransaction = new TransactionTemplate(sources.manager); + joinTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + joinTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + joinTransaction.setReadOnly(false); + scopes = + new AccountCanonicalPublicRealmScopeOwner( + new AccountPlayerBootstrapCallerVerifier(jwt, sources.accounts, unusedBrowserSessions), + genuineTargets, + publicEntitlements, + sources.accounts, + members, + fresh, + tenantEvents, + retainedScopes, + jwt, + tokens, + clock, + sources.manager, + namespace); + var owner = + new AccountPlayerAdmissionEntitlementOwner( + sources.dsl, + sources.accounts, + login.admissionCallerVerifier(), + login.issuanceRepository(), + snapshots, + retainedScopes, + unusedPaidRepository, + unusedProvider, + demos, + tenantEvents, + genuineTargets, + sources.manager, + clock, + namespace); + receiver = new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); + assertAbsentMembership(); + } + + public AccountPlayerAdmissionSharedOwnerFixture login() { + return login; + } + + public AccountJwtJwksTrustedSource trustedJwksSource() { + return login.trustedJwksSource(); + } + + /** The receiver creates only an explicit private mTLS listener when its caller requests one. */ + public AccountPlayerAdmissionEntitlementGrpcService receiver() { + return receiver; + } + + /** + * Uses the real scope owner, signed token, retained readback and protected target client. Only + * this scope-invocation peer is stipulated; no authenticated socket or public ingress is proved. + */ + public RealmScope issueScopeWithControlledGameSessionCaller( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + Objects.requireNonNull(caller, "Controlled direct-text caller is required"); + Objects.requireNonNull(target, "Actual selected target is required"); + if (!login.accountId().equals(caller.accountId()) + || !sources.tenant.equals(caller.tenantId()) + || !sources.tenant.equals(target.tenantId())) { + throw new IllegalArgumentException("Scope must use the separate player and shared tenant"); + } + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/game-session-service") + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + RealmScope result = scopes.issueDirectTextScope(caller, target); + assertThat(result.membership().accountId()).isEqualTo(login.accountId()); + assertThat(result.membership().tenantId()).isEqualTo(sources.tenant); + assertThat(result.membership().current()).isEmpty(); + assertThat(result.entitlement().sourceKind()).isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(result.entitlement().entitlementVersion()).isEqualTo(demo.entitlementVersion()); + assertAbsentMembership(); + return result; + } finally { + context.detach(previous); + } + } + + /** + * Explicit owner-local first JOIN. Request and caller binding are controlled correlation inputs, + * not authentication supplied by this coordinator. Signed scope/current target checks precede + * SQL; they establish no cross-service hold through commit. Replay uses the identical inputs. + */ + public CanonicalJoinTerminalProof commitFirstJoin( + RealmScope issued, String requestId, String controlledCallerBinding) { + Objects.requireNonNull(issued, "Actual issued realm scope is required"); + var scope = scopeReader.read(login.accountId(), issued.scope().connectScopeId()); + assertThat(scope).isEqualTo(issued.scope()); + assertThat(scope.tenantId()).isEqualTo(sources.tenant); + requireCurrentTarget(issued, scope); + var before = + joinTransaction.execute( + status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding); + return authority.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, login.accountId()); + }); + // The second actual target read detects pre-commit drift, but is intentionally not a hold. + requireCurrentTarget(issued, scope); + CanonicalJoinTerminalProof proof = + joinTransaction.execute( + status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + requireLiveScope(scope); + var currentDemo = demos.revalidate(demo); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + controlledCallerBinding, + currentDemo.allowPublicJoin(), + currentDemo.entitlementVersion()); + var committed = + firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); + assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, committed); + requireLiveScope(scope); + return committed; + }); + Objects.requireNonNull(proof, "Committed first-JOIN receipt is required"); + // Independent transaction proves durable terminal replay, not merely same-transaction reads. + var replay = + joinTransaction.execute( + status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + requireLiveScope(scope); + assertThat( + operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding)) + .isFalse(); + var repeated = + firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); + assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, repeated); + return repeated; + }); + assertThat(replay).isEqualTo(proof); + assertThat(scopeReader.read(login.accountId(), scope.connectScopeId())).isEqualTo(scope); + var after = + sources.tx( + () -> + authority.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, login.accountId())); + Objects.requireNonNull(before, "Original LOGIN authority sources are required"); + assertThat(after.issuer()).isEqualTo(before.issuer()); + assertThat(after.account()).isEqualTo(before.account()); + assertThat(after.issuanceFence()).isEqualTo(before.issuanceFence()); + login.assertCreatorRemainsNonAdmitting(); + verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); + return proof; + } + + /** Positive membership source evidence only, after the same real receiver/client reread. */ + public void assertAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence evidence) { + Objects.requireNonNull(evidence, "Actual Account receiver evidence is required"); + evidence.requireCurrentAt(clock.instant()); + var current = sources.tx(() -> snapshots.readCurrent(login.accountId(), sources.tenant)); + assertThat(evidence.membershipSource()).isEqualTo(current); + assertAdmittingSnapshot(current); + sources.tx(() -> demos.revalidate(demo)); + login.assertCreatorRemainsNonAdmitting(); + verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); + } + + private void requireCurrentTarget(RealmScope issued, CanonicalJoinScopeV2 scope) { + var selector = + new RetainedTargetSelector( + UUID.randomUUID(), + scope.accountId(), + namespace, + scope.tenantId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + var resolved = targets.resolvePublishedRealmAdmissionTarget(selector); + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + assertThat(resolved.selector()).isEqualTo(selector); + var current = targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + assertThat(current.selector()).isEqualTo(resolved.strictSelector()); + assertThat(current.currentTarget()) + .isEqualTo(resolved.currentTarget()) + .isEqualTo(issued.target()); + requireLiveScope(scope); + } + + private void requireLiveScope(CanonicalJoinScopeV2 scope) { + Instant now = clock.instant(); + if (now.isBefore(Instant.parse(scope.evaluatedAt())) + || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) { + throw new IllegalStateException("Original signed first-JOIN scope is no longer current"); + } + } + + /** All rows are read beneath the same Account fence as the actual terminal owner. */ + private void assertFirstJoinReceipt( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + CanonicalJoinTerminalProof proof) { + var operation = operations.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); + assertThat(operation.status()).isEqualTo("COMMITTED"); + assertThat(operation.outcome()).isEqualTo("JOINED"); + assertThat(operation.callerBinding()).isEqualTo(callerBinding); + assertThat(operation.scopeTokenHash()) + .isEqualTo(AccountJoinDigest.tokenHash(scope.connectScopeId())); + assertThat(operation.connectScopeDigest()).isEqualTo(AccountJoinDigest.scopeV2(scope)); + assertThat(operation.intentDigest()) + .isEqualTo(AccountJoinDigest.intentV2(requestId, scope, callerBinding)); + assertThat(operation.terminalProof()).isEqualTo(proof); + assertThat(proof.entitlementVersion()).isEqualTo(demo.entitlementVersion()); + assertThat(proof.membershipVersion()).isEqualTo(2L); + assertThat(proof.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(proof.eventSequence()).isEqualTo(1L); + var member = + members.findFreshMembershipForUpdate(login.accountId(), sources.tenant).orElseThrow(); + assertThat(member.getId()).isEqualTo(proof.membershipId()); + assertThat(member.getAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); + var pair = pairs.readForUpdate(login.accountId(), sources.tenant).orElseThrow(); + assertThat(pair.membershipExists()).isTrue(); + assertThat(pair.membershipVersion()).isEqualTo(proof.membershipVersion()); + assertThat(pair.membershipAuthorityGeneration()) + .isEqualTo(proof.membershipAuthorityGeneration()); + assertThat(pair.eventSequence()).isEqualTo(proof.eventSequence()); + assertThat(pair.eventId()).isEqualTo(proof.eventId()); + assertThat(pair.eventDigest()).isEqualTo(proof.eventDigest()); + assertThat(pair.lastTransitionInvalidated()).isFalse(); + var checkpoint = outbox.readCheckpoint(proof.eventStreamKey()).orElseThrow(); + assertThat(checkpoint.outboxSequence()).isEqualTo(proof.eventSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(proof.eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(proof.eventDigest()); + var event = outbox.findEvent(proof.eventStreamKey(), proof.eventSequence()).orElseThrow(); + assertThat(event.requestId()).isEqualTo(requestId); + assertThat(event.eventId()).isEqualTo(proof.eventId()); + assertThat(event.eventDigest()).isEqualTo(proof.eventDigest()); + var decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + assertThat(event.payload()).containsExactly(decoded.canonicalJsonUtf8()); + var audit = audits.findCanonicalTenantEnvelopeForUpdate(proof.auditEventId()).orElseThrow(); + assertThat(audit.tenantUuid()).isEqualTo(sources.tenant); + assertThat(audit.tenantIdentityVersion()).isEqualTo(2); + assertThat(audit.eventType()).isEqualTo("ACCOUNT_JOINED_PUBLIC_PRODUCTION"); + assertThat(audit.producerService()).isEqualTo("account-service"); + assertThat(audit.payloadDigest()).isEqualTo(proof.auditPayloadDigest()); + assertThat(audit.occurredAt()).isEqualTo(proof.auditOccurredAt()); + assertAdmittingSnapshot(snapshots.readCurrent(login.accountId(), sources.tenant)); + } + + private void assertAdmittingSnapshot(Snapshot current) { + assertThat(current.accountId()).isEqualTo(login.accountId().toString()); + assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); + assertThat(current.membershipExists()).isTrue(); + assertThat(current.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(current.gameplayAdmissionAllowed()).isTrue(); + assertThat(current.roles()).containsExactly("player"); + assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "2"); + assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); + } + + private T transactional(T target, Class type) { + var proxy = new ProxyFactory(target); + proxy.setProxyTargetClass(true); + proxy.addAdvice( + new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); + return type.cast(proxy.getProxy(type.getClassLoader())); + } + + /** Exact current source comparison after the receiving client has authenticated the response. */ + public void assertNonAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence evidence) { + Objects.requireNonNull(evidence, "Actual Account receiver evidence is required"); + evidence.requireCurrentAt(clock.instant()); + var current = sources.tx(() -> snapshots.readCurrent(login.accountId(), sources.tenant)); + assertThat(evidence.membershipSource()).isEqualTo(current); + assertAbsentMembership(); + } + + /** Confirms actual absence enrollment and current tenant DEMO source without editing history. */ + public void assertAbsentMembership() { + sources.tx( + () -> { + var current = snapshots.readCurrent(login.accountId(), sources.tenant); + assertThat(current.accountId()).isEqualTo(login.accountId().toString()); + assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); + assertThat(current.membershipExists()).isFalse(); + assertThat(current.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(current.gameplayAdmissionAllowed()).isFalse(); + assertThat(current.roles()).isEmpty(); + assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "1"); + assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(demos.revalidate(demo)).isEqualTo(demo); + return null; + }); + login.assertCreatorRemainsNonAdmitting(); + verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); + } + + private static void requireFirstDemoRequest( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence creation) { + Objects.requireNonNull(request, "Explicit controlled demo policy is required"); + if (!creation.canonicalTenantId().equals(request.canonicalTenantId()) + || !creation.creationRequestId().equals(request.tenantCreationRequestId()) + || !creation.requestDigest().equals(request.tenantCreationRequestDigest()) + || request.expectedEntitlementVersion() != null + || request.expectedTenantAuthorityGeneration() != null + || request.expectedTenantAuthoritySourceVersion() != null) { + throw new IllegalArgumentException( + "First DEMO request must preserve exact creation provenance"); + } + } + + private static String scopeSigningKey() { + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static T excluded(Class type) { + return mock( + type, + invocation -> { + throw new AssertionError( + "Excluded paid/browser dependency invoked: " + type.getSimpleName()); + }); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java new file mode 100644 index 0000000000..6445ea8dc6 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -0,0 +1,455 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import tools.jackson.databind.json.JsonMapper; + +/** + * Shared-source Account LOGIN composition for the original creator or a separate global player. SQL + * owners, primary verification, signer correspondence, encrypted response recovery, and physical + * Redis registration/projection are real; upstream creator/legal/platform evidence, key custody, + * the newly stored OTP, and the verified caller argument remain controlled inputs. + * + *

This helper borrows the original fixture's connections and does not activate runtime wiring. + * Its ACTIVE tenantAdmin creator membership remains non-admitting. LOGIN establishes global + * identity only; no positive membership, entitlement, connect scope, or PLAY authority is made. + */ +public final class AccountPlayerAdmissionSharedOwnerFixture { + private static final SecureRandom RANDOM = new SecureRandom(); + private static final int REGISTRY_BYTES = + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; + private static final long REGISTRY_CLEANUP_MILLIS = 30_000L; + private final AccountControlUiOwnerSourcesFixture sources; + private final Account account; + private final AccountJwtJwksTrustedSource publicSource; + private final Clock clock; + private final AccountCoordinationPinnedConnectionProvider connections; + private final AccountGameplayDelegationIssuanceRepository issuance; + private final AccountAuthoritySourceEvidenceRepository authoritySources; + private final AccountGameplayDelegationAuthorityProjection projection; + private final AccountGameplayCanonicalLoginOwner login; + private final AccountGameplayPrimaryCredentialVerifier verifier; + private final AccountGameplayDelegationCommittedIssuanceOwner committedOwner; + private final String otp = "shared-login-" + UUID.randomUUID(); + + public AccountPlayerAdmissionSharedOwnerFixture( + AccountControlUiOriginalOrderFixture original, Path temporary) throws Exception { + this(original, temporary, Clock.systemUTC()); + } + + public AccountPlayerAdmissionSharedOwnerFixture( + AccountControlUiOriginalOrderFixture original, Path temporary, Clock clock) throws Exception { + this(original, temporary, clock, false); + } + + static AccountPlayerAdmissionSharedOwnerFixture freshGlobalPlayer( + AccountControlUiOriginalOrderFixture original, Path temporary, Clock clock) throws Exception { + return new AccountPlayerAdmissionSharedOwnerFixture(original, temporary, clock, true); + } + + private AccountPlayerAdmissionSharedOwnerFixture( + AccountControlUiOriginalOrderFixture original, + Path temporary, + Clock clock, + boolean separateGlobalPlayer) + throws Exception { + Objects.requireNonNull(original, "Original Account owner fixture is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + sources = original.preparedOriginalCreator().sources(); + account = + separateGlobalPlayer + ? sources.createGlobalAccount("shared-player-" + UUID.randomUUID()) + : sources.account; + publicSource = original.publicSource; + connections = original.gameplayConnectionProvider(); + assertCreatorRemainsNonAdmitting(); + assertThat(sources.challenges.findByAccountId(account.getId())).isEmpty(); + + var generations = new AccountAuthorityGenerationRepository(sources.dsl); + var outbox = new AccountAuthorityOutboxRepository(sources.dsl); + authoritySources = + new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); + sources.tx( + () -> { + authoritySources.initializeIssuerIfAbsent(GameSessionAccountDelegationProfile.ISSUER); + return null; + }); + var bundles = new AccountAuthEvidenceBundleRepository(sources.dsl, generations, outbox); + var issuanceTarget = + new AccountGameplayDelegationIssuanceRepository(sources.dsl, authoritySources, bundles); + // Preserve MANDATORY writes and independent REQUIRES_NEW committed-proof readbacks. + var issuanceProxy = new ProxyFactory(issuanceTarget); + issuanceProxy.setProxyTargetClass(true); + issuanceProxy.addAdvice( + new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); + issuance = + (AccountGameplayDelegationIssuanceRepository) + issuanceProxy.getProxy( + AccountGameplayDelegationIssuanceRepository.class.getClassLoader()); + var cryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring(temporary).toString())); + var envelopes = + new AccountGameplayDelegationResponseEnvelopeRepository( + sources.dsl, authoritySources, bundles, issuance, cryptography); + var lifecycle = original.signerFixture; + var signer = + new AccountGameplayDelegationSigner( + issuance, + lifecycle.desired, + lifecycle.trust, + lifecycle.api, + original.publicSource, + new AccountGameplayDelegationResponseEnvelopeService(envelopes), + sources.manager, + clock, + lifecycle.privateRoot, + Path.of("current.key"), + lifecycle.publicRoot, + Path.of("jwks.json")); + var redis = + new AccountGameplayDelegationRedisClient( + connections, + loginScriptCatalog(), + new AcknowledgementRequirements(1, 1, 5_000), + clock, + REGISTRY_BYTES, + AccountPlayerAdmissionSharedOwnerFixture.class.getClassLoader()); + projection = + new AccountGameplayDelegationAuthorityProjection(authoritySources, sources.manager, redis); + var registry = + new AccountGameplayDelegationTokenRegistry( + issuance, sources.manager, redis, clock, REGISTRY_BYTES, REGISTRY_CLEANUP_MILLIS); + var commit = + new AccountGameplayDelegationIssuanceCommitService( + signer, registry, projection, issuance, sources.manager, clock); + committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signer, registry, sources.manager, clock); + var recovery = + new AccountGameplayDelegationResponseRecoveryOwner( + envelopes, committedOwner, sources.manager); + verifier = new AccountGameplayPrimaryCredentialVerifier(sources.primary); + login = + new AccountGameplayCanonicalLoginOwner( + sources.accounts, + issuance, + digestKeys(clock), + commit, + recovery, + sources.manager, + clock); + // Control-UI consumed the original challenge. Never resurrect or reuse that consumed row. + sources.installGlobalOtp(account, otp); + } + + public UUID accountId() { + return account.getAccountUuid(); + } + + public FreshTenantCreationEvidence creationEvidence() { + return sources.creationEvidence; + } + + /** The test supplies caller coordinates; the actual owner binds and consumes the fresh OTP. */ + public CanonicalGameplayLoginRequest loginRequest( + UUID requestId, GameplayCredentialSourceContext context) { + return new CanonicalGameplayLoginRequest(requestId, account.getEmail(), otp, context); + } + + /** + * Real stored OTP input for the canonical receiver; source/socket custody is caller-controlled. + */ + public AuthenticateRequest wireLoginRequest( + UUID requestId, GameplayCredentialSourceContext context) { + var request = loginRequest(requestId, context); + if (!"trusted_tcp_proxy".equals(context.transportClass())) { + throw new IllegalArgumentException("Canonical receiver requires trusted TCP Proxy context"); + } + return AuthenticateRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setEmail(account.getEmail()) + .setPassword(otp) + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(context.contextId().toString()) + .setCanonicalClientAddress(context.canonicalClientAddress()) + .setTransportClass( + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + } + + /** The caller must install the real TLS peer interceptor on its private mTLS server. */ + public AccountGameplayAuthenticateReceiver authenticateReceiver(String namespace) { + if (!creationEvidence().targetNamespace().equals(namespace)) { + throw new IllegalArgumentException("Receiver namespace must match the shared tenant source"); + } + return new AccountGameplayAuthenticateReceiver(login, verifier, namespace); + } + + /** Actual receipt-backed public source, not a replacement JWKS document. */ + public AccountJwtJwksTrustedSource trustedJwksSource() { + return publicSource; + } + + AccountGameplayAdmissionCallerVerifier admissionCallerVerifier() { + return new AccountGameplayAdmissionCallerVerifier(publicSource, committedOwner, clock); + } + + AccountGameplayDelegationIssuanceRepository issuanceRepository() { + return issuance; + } + + /** Direct owner invocation, not evidence of an authenticated transport or deployed caller. */ + public InitialGameplayLoginResult authenticate( + CanonicalGameplayLoginRequest request, String verifiedGameSessionWorkload) { + return login.authenticate(request, verifiedGameSessionWorkload, verifier); + } + + /** Exact SQL, active Redis, and projection readback; identity remains distinct from admission. */ + public void assertCommittedNonAdmittingLogin(InitialGameplayLoginResult result) { + assertThat(result.accountId()).isEqualTo(accountId()); + assertThat(result.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertCommittedNonAdmittingLogin( + result.requestId(), + result.callerContextId(), + result.tokenJti(), + result.tokenSha256(), + result.expiresAtEpochSecond()); + } + + /** Compares nonsecret receiving-client evidence to actual SQL, Redis and current sources. */ + public void assertCommittedNonAdmittingLogin( + UUID requestId, + UUID callerContextId, + UUID tokenJti, + String tokenSha256, + long expiresAtEpochSecond) { + assertThat(sources.challenges.findByAccountId(account.getId())).isEmpty(); + var replay = sources.tx(() -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(replay.state()).isEqualTo(GameplayLoginReplayState.COMMITTED); + var committed = sources.tx(() -> issuance.readCurrentCommittedCandidate(requestId)); + assertThat(committed.identity()).isEqualTo(replay.identity()); + assertThat(committed.identity().accountId()).isEqualTo(accountId()); + assertThat(committed.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(committed.identity().tokenJti()).isEqualTo(tokenJti); + assertThat(committed.tokenSha256()).isEqualTo(tokenSha256); + assertThat(committed.commitProofSha256()).isNotBlank(); + assertThat(committed.registrationLocalAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committed.registrationReplicaAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committed.registryAbsoluteExpiryMillis()) + .isEqualTo( + Math.addExact( + Math.multiplyExact(expiresAtEpochSecond, 1_000L), REGISTRY_CLEANUP_MILLIS)); + var snapshot = + sources.tx( + () -> + authoritySources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId())); + byte[][] expected = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot); + var observation = projection.observeCurrent(accountId()); + assertThat(observation.issuerGeneration()).isEqualTo(snapshot.issuer().generation()); + assertThat(observation.accountGeneration()).isEqualTo(snapshot.account().generation()); + try (var connection = connections.openPinnedConnection()) { + var commands = connection.sync(); + assertThat(commands.aclWhoami()) + .isEqualTo(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + byte[] tokenKey = ascii(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + tokenSha256); + var active = + GameSessionAccountDelegationRegistryRecord.decode(commands.get(tokenKey), REGISTRY_BYTES); + assertThat(active.state()).isEqualTo("active"); + assertThat(active.tokenHash()).isEqualTo(tokenSha256); + assertThat(active.requestId()).isEqualTo(requestId.toString()); + assertThat(commands.pexpiretime(tokenKey)) + .isEqualTo(committed.registryAbsoluteExpiryMillis()); + assertThat( + commands.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER))) + .containsExactly(expected[0]); + assertThat( + commands.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + + accountId()))) + .containsExactly(expected[1]); + } + assertCreatorRemainsNonAdmitting(); + if (!accountId().equals(sources.account.getAccountUuid())) { + sources.tx( + () -> { + var fresh = + new FreshTenantIdentityAssociationRepository( + sources.dsl, creationEvidence().targetNamespace()); + var memberships = + new AccountTenantMembershipRepository( + sources.dsl, + sources.accounts, + fresh, + new AccountMembershipPairAuthorityRepository(sources.dsl)); + assertThat(memberships.findFreshMembership(accountId(), sources.tenant)).isEmpty(); + return null; + }); + } + } + + /** Real canonical membership and role readback, with the original source tuple unchanged. */ + public void assertCreatorRemainsNonAdmitting() { + UUID creatorId = sources.account.getAccountUuid(); + sources.tx( + () -> { + var fresh = + new FreshTenantIdentityAssociationRepository( + sources.dsl, creationEvidence().targetNamespace()); + assertThat(fresh.read(sources.tenant)).contains(creationEvidence()); + var pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); + var memberships = + new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); + var membership = memberships.findFreshMembership(creatorId, sources.tenant).orElseThrow(); + assertThat(membership.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(membership.getAuthorityProvenance()).isEqualTo("TENANT_CREATION"); + assertThat(membership.isGameplayAdmissionAllowed()).isFalse(); + var pair = pairs.readPositive(creatorId, sources.tenant).orElseThrow(); + var roles = + new AccountTenantMembershipRoleSnapshotRepository(sources.dsl) + .findForCanonicalUpdate( + creatorId, + sources.tenant, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + assertThat(roles.roles()).containsExactly("tenantAdmin"); + return null; + }); + } + + private static Path writeResponseKeyring(Path temporary) throws IOException { + Path root = + Files.createTempDirectory(Files.createDirectories(temporary), "shared-login-keyring-") + .toAbsolutePath(); + byte[] key = new byte[32]; + RANDOM.nextBytes(key); + try { + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive shared-login " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n", + StandardCharsets.US_ASCII); + } finally { + Arrays.fill(key, (byte) 0); + } + return root; + } + + private static AccountGameplayCredentialRequestDigestKeySource digestKeys(Clock clock) { + byte[] key = new byte[32]; + RANDOM.nextBytes(key); + CredentialDigestKey digest; + try { + digest = + new CredentialDigestKey( + "shared-login", + new SecretKeySpec(key, "HmacSHA256"), + Instant.now(clock).plusSeconds(3_600)); + } finally { + Arrays.fill(key, (byte) 0); + } + return new AccountGameplayCredentialRequestDigestKeySource() { + @Override + public CredentialDigestKey currentKey() { + return digest; + } + + @Override + public CredentialDigestKey requireKey(String keyId) { + if (!digest.keyId().equals(keyId)) { + throw new IllegalStateException("Unknown test-only LOGIN digest key"); + } + return digest; + } + }; + } + + private static RedisScriptCatalog loginScriptCatalog() throws IOException { + List descriptors = new ArrayList<>(); + var json = JsonMapper.builder().build(); + for (String resource : + List.of( + "/redis/scripts/account-game-session-delegation-pending-register.json", + "/redis/scripts/account-game-session-delegation-activate-committed.json", + "/redis/scripts/account-game-session-delegation-authority-project-issuer.json")) { + try (var input = + AccountPlayerAdmissionSharedOwnerFixture.class.getResourceAsStream(resource)) { + if (input == null) throw new IllegalStateException("Account LOGIN descriptor is absent"); + descriptors.add(json.readValue(input, RedisScriptDescriptor.class)); + } + } + return RedisScriptCatalog.fromContributions( + List.of( + new AccountGenerationProjectionRedisScriptContribution(), + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.copyOf(descriptors); + } + })); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index e7c312d99a..9da1ecfd40 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -64,12 +64,14 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerAdmissionSharedOwnerFixture; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionAcquisitionGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionSettlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionSettlementService; @@ -584,6 +586,9 @@ private void compose( "Created placement proof requires the committed coupled owner path"); } UUID tenant = UUID.randomUUID(); + var sharedAuthoredSource = controlledSource("controlled-upstream", tenant); + var sharedCreation = + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sharedAuthoredSource); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT.getJdbcUrl(), @@ -592,7 +597,7 @@ private void compose( REDIS.getHost(), REDIS.getMappedPort(6379), proofDirectory.resolve("account"), - tenant, + sharedCreation, true); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { @@ -682,7 +687,14 @@ public void attachAccountRedemptionProjection( var createdPublication = new AtomicReference(); var preparedInput = preparationInputs( - world, gs, tuple, claim.get(), tenant, playerCreatedPlacement, createdPublication); + world, + gs, + tuple, + claim.get(), + tenant, + playerCreatedPlacement, + createdPublication, + sharedAuthoredSource); var input = refusal == Refusal.MISMATCHED_ATTEMPT ? new WorldCanonicalInstancePreparation.Input( @@ -1860,6 +1872,7 @@ public void close() {} exerciseCoupledCanonicalInitialAdmission( gs, world, + account, issuer, currentAttempt, proofDirectory, @@ -2426,6 +2439,7 @@ private static String prefixedSha256(byte[] bytes) { private static void exerciseCoupledCanonicalInitialAdmission( Database gs, Database world, + AccountControlUiOriginalOrderFixture account, AccountOriginalStartSessionAuthorizationProofFixture issuer, GrpcOriginalStartSessionCurrentAttemptClient currentAttempt, Path proofDirectory, @@ -3008,6 +3022,7 @@ private static void exerciseCoupledCanonicalInitialAdmission( composeActualEntityWorldRegionPrerequisite( gs, world, + account, proofDirectory, pki, factory, @@ -3088,6 +3103,7 @@ private static void assertAccountAdmissionProtectionSettled( private static void composeActualEntityWorldRegionPrerequisite( Database gs, Database world, + AccountControlUiOriginalOrderFixture account, Path proofDirectory, WorldOriginalStartSessionPreparationProofPki worldPki, GrpcChannelFactory channels, @@ -3436,13 +3452,22 @@ private static void composeActualEntityWorldRegionPrerequisite( try { var worldEndpoints = new ServiceEndpointsProperties(); worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); - WorldPublishedAdmissionSourceComposition.exercise( - proofDirectory, - gs.dsl(), - currentTarget, - accountUuid, - worldEndpoints, - worldPki.client("game-session-service")); + // Authenticate after the earlier password/authority mutation has settled. The + // creation tuple is shared by Account, World and GS; the caller is still controlled. + var loginOwner = + new AccountPlayerAdmissionSharedOwnerFixture( + account, proofDirectory.resolve("shared-login")); + var loginRequest = + loginOwner.loginRequest( + UUID.randomUUID(), + new GameplayCredentialSourceContext( + UUID.randomUUID(), "192.0.2.42", "direct-text")); + var loginResult = + loginOwner.authenticate( + loginRequest, "spiffe://firemud/ns/firemud/sa/game-session-service"); + loginOwner.assertCommittedNonAdmittingLogin(loginResult); + assertThat(loginResult.accountId()).isEqualTo(accountUuid); + assertThat(loginOwner.creationEvidence()).isEqualTo(account.creationEvidence()); var initialLocationClient = new CanonicalInitialPlayerLocationClient( worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); @@ -3549,6 +3574,15 @@ private static void composeActualEntityWorldRegionPrerequisite( assertThat(regionProofs.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); assertThat(regionProofs.expiredGrantRejectedWithoutStateChange()).isTrue(); } + // Run the genuine second-player DEMO mutation after original placement assertions. + WorldPublishedAdmissionSourceComposition.exercise( + proofDirectory, + gs.dsl(), + currentTarget, + accountUuid, + account, + worldEndpoints, + worldPki.client("game-session-service")); } finally { shutdown(worldLocationServer); entityReceiptClient.close(); @@ -4168,11 +4202,11 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, UUID tenant, boolean playerCreatedPlacement, - AtomicReference createdPublication) + AtomicReference createdPublication, + AuthoredWorldSourceEvidence source) throws Exception { var intakeRepository = new WorldAuthoredSourceIntakeRepository(world.dsl()); var versionRepository = new WorldAuthoredVersionIdentityRepository(world.dsl()); - var source = controlledSource("controlled-upstream", tenant); var intake = Objects.requireNonNull( world diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java new file mode 100644 index 0000000000..f1dfba1329 --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerAdmissionSharedEntitlementFixture; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; + +/** + * Actual LOGIN and PLAYER_ADMISSION producer/consumer with a genuine absent player and shared + * Account/GS/World sources, followed by genuine owner-local first JOIN and positive source read. + * DEMO policy, caller coordinates, PKI and local custody callbacks are controlled. No public + * ingress, installed custody, World hold across JOIN, runtime activation or PLAY is proved. + */ +final class WorldPlayerAdmissionEntitlementComposition { + private WorldPlayerAdmissionEntitlementComposition() {} + + static void exercise( + Path root, + AccountControlUiOriginalOrderFixture original, + CanonicalGameplayAdmissionDecisionReadClient targets, + CanonicalPlayableTarget target) + throws Exception { + var clock = Clock.systemUTC(); + String namespace = target.targetNamespace(); + Path directory = Files.createDirectories(root.resolve("player-admission")); + var pki = + LoopbackMtlsTestPki.create( + directory, + "Controlled genuine player admission sources", + new LoopbackMtlsTestPki.IdentitySpec( + "gs", "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + namespace + "/sa/account-service", true)); + var creation = original.creationEvidence(); + var demo = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + creation.canonicalTenantId(), + creation.creationRequestId(), + creation.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)); + var fixture = + new AccountPlayerAdmissionSharedEntitlementFixture( + original, directory, targets, demo, clock); + var loginOwner = fixture.login(); + var keys = pki.keyManagerFactory(pki.identity("account")); + var trust = pki.trustManagerFactory(); + Server loginServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer(keys)) + .trustManager(trust) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + loginOwner.authenticateReceiver(namespace), new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + Server entitlementServer = + fixture.receiver().createUnregisteredServer("127.0.0.1:0", keys, trust); + entitlementServer.start(); + try { + var loginEndpoints = new ServiceEndpointsProperties(); + loginEndpoints.setAccountService("localhost:" + loginServer.getPort()); + var entitlementEndpoints = new ServiceEndpointsProperties(); + entitlementEndpoints.setAccountService("localhost:" + entitlementServer.getPort()); + var tls = pki.clientProperties(directory, pki.identity("gs")); + var channels = new GrpcChannelFactory(); + var source = fixture.trustedJwksSource(); + var verifier = + new AccountAsymmetricJwtVerifier( + new AccountPublicJwksCache( + source, source.sourceIdentity(), clock, Duration.ofSeconds(30)), + clock); + try (var loginClient = + new CanonicalGameplayLoginAccountClient( + loginEndpoints, + tls, + channels, + BlockingGrpcStubCustomizer.noop(), + namespace, + clock, + Duration.ofSeconds(15), + verifier); + var entitlementClient = + new AccountPlayerAdmissionEntitlementClient( + entitlementEndpoints, tls, channels, namespace, clock)) { + loginClient.initialize(); + entitlementClient.init(); + var wireRequest = + loginOwner.wireLoginRequest( + UUID.randomUUID(), + new GameplayCredentialSourceContext( + UUID.randomUUID(), "192.0.2.42", "trusted_tcp_proxy")); + // Controlled original custody; the returned credential and Account currentness are real. + try (var login = loginClient.authenticate(wireRequest, () -> true)) { + var evidence = login.evidence(); + loginOwner.assertCommittedNonAdmittingLogin( + evidence.requestId(), + evidence.callerContextId(), + evidence.tokenJti(), + evidence.tokenSha256(), + evidence.expiresAtEpochSecond()); + var transport = new ObservedDirectTextTransport("1", UUID.randomUUID()); + var realmScope = + fixture.issueScopeWithControlledGameSessionCaller( + new DirectTextCallerContext( + evidence.accountId(), + target.canonicalTenantId(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + transport.proxyConnectionId().toString(), + UUID.randomUUID().toString()), + new DirectTextJoinTarget( + target.canonicalTenantId(), + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion())); + var scope = realmScope.scope(); + var issued = + DirectTextIssuedConnectScope.fromAccountResponse( + evidence.accountId().toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scope.connectScopeId()) + .setEvaluatedAt(scope.evaluatedAt()) + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) + .build(), + clock); + var coordinates = + new InitialGameplayLoginAttemptCoordinates( + evidence.requestId(), evidence.callerContextId(), 1L); + // This encodes a desired value only. No Redis installed-custody proof is claimed. + var lobby = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(coordinates, login), + transport, + target, + issued); + var received = + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); + fixture.assertNonAdmittingEvidence(received); + assertThat(received.fields()).containsEntry("variant", "PLAYER_ADMISSION"); + // Actual Account owner transition; caller binding is controlled and no World hold + // spans this JOIN transaction. Reuse only the still-current verified LOGIN result. + fixture.commitFirstJoin( + realmScope, UUID.randomUUID().toString(), transport.proxyConnectionId().toString()); + var joined = + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); + fixture.assertAdmittingEvidence(joined); + assertThatThrownBy( + () -> + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) + .isInstanceOf(RuntimeException.class); + } + } + } finally { + stop(entitlementServer); + } + } finally { + stop(loginServer); + } + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java index 2a9e92090d..3cf1298364 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -38,9 +38,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Real GS OPEN/current publication reader and World ACTIVE owner over authenticated sockets. - * Upstream Game Design publication and ephemeral PKI remain controlled test inputs. This reads - * evidence only, and does not establish LOGIN, entitlement, gameplay binding or activation. + * Real GS OPEN/current publication and World ACTIVE reads over authenticated sockets, followed by + * actual Account LOGIN, absent-player entitlement, owner-local first JOIN and positive source + * reread. Game Design publication, DEMO policy, PKI, caller coordinates and custody callbacks are + * controlled. No public ingress, World hold across JOIN, installed custody or activation is proved. */ final class WorldPublishedAdmissionSourceComposition { private WorldPublishedAdmissionSourceComposition() {} @@ -50,6 +51,8 @@ static void exercise( DSLContext gs, CanonicalPlayableTarget target, UUID account, + net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture + originalAccount, ServiceEndpointsProperties worldEndpoints, CommonGrpcClientProperties worldTls) throws Exception { @@ -195,6 +198,8 @@ public void listPublishedRealmEntryPolicies( target.pointerVersion()); assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) .isInstanceOf(RuntimeException.class); + WorldPlayerAdmissionEntitlementComposition.exercise( + root, originalAccount, accountClient, target); } } finally { stop(receiver); From 142c9ba818d8c8477e610466b2c644060eea979c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 06:28:03 +1300 Subject: [PATCH 12/66] test: qualify physical login lifecycle with fresh player authority --- services/account-service/build.gradle.kts | 2 + ...ountPlayerAdmissionSharedOwnerFixture.java | 17 +- .../game-session-service/build.gradle.kts | 3 + ...meplayLoginPhysicalCompositionFixture.java | 385 ++++++++++++++++++ ...ationOwnerCompositionCrossServiceTest.java | 23 +- ...PlayerAdmissionEntitlementComposition.java | 51 ++- ...ldPublishedAdmissionSourceComposition.java | 15 +- 7 files changed, 458 insertions(+), 38 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 5b1ceb456f..0c89f71487 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -197,10 +197,12 @@ val accountOriginalOrderProofJar by tasks.registering(Jar::class) { include("redis/lua/account-game-session-delegation-pending-register.lua") include("redis/lua/account-game-session-delegation-activate-committed.lua") include("redis/lua/account-game-session-delegation-authority-project.lua") + include("redis/lua/account-initial-gameplay-login-dispose.lua") include("redis/account_generation_projection_cas.lua") include("redis/scripts/account-game-session-delegation-pending-register.json") include("redis/scripts/account-game-session-delegation-activate-committed.json") include("redis/scripts/account-game-session-delegation-authority-project-issuer.json") + include("redis/scripts/account-initial-gameplay-login-dispose.json") include("redis/scripts/account-generation-projection-cas.json") } } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java index 6445ea8dc6..8d9b53e240 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; @@ -75,6 +76,7 @@ public final class AccountPlayerAdmissionSharedOwnerFixture { private final AccountGameplayCanonicalLoginOwner login; private final AccountGameplayPrimaryCredentialVerifier verifier; private final AccountGameplayDelegationCommittedIssuanceOwner committedOwner; + private final AccountInitialGameplayLoginDisposalOwner disposal; private final String otp = "shared-login-" + UUID.randomUUID(); public AccountPlayerAdmissionSharedOwnerFixture( @@ -165,6 +167,11 @@ private AccountPlayerAdmissionSharedOwnerFixture( var registry = new AccountGameplayDelegationTokenRegistry( issuance, sources.manager, redis, clock, REGISTRY_BYTES, REGISTRY_CLEANUP_MILLIS); + disposal = + new AccountInitialGameplayLoginDisposalOwner( + new AccountInitialGameplayLoginDisposalRepository(sources.dsl), + registry, + sources.manager); var commit = new AccountGameplayDelegationIssuanceCommitService( signer, registry, projection, issuance, sources.manager, clock); @@ -224,12 +231,15 @@ public AuthenticateRequest wireLoginRequest( .build(); } - /** The caller must install the real TLS peer interceptor on its private mTLS server. */ + /** + * The caller must install the real TLS peer interceptor on its private mTLS server. Known-token + * retirement uses the same SQL/Redis owners; unqualified no-binding disposal remains PENDING. + */ public AccountGameplayAuthenticateReceiver authenticateReceiver(String namespace) { if (!creationEvidence().targetNamespace().equals(namespace)) { throw new IllegalArgumentException("Receiver namespace must match the shared tenant source"); } - return new AccountGameplayAuthenticateReceiver(login, verifier, namespace); + return new AccountGameplayAuthenticateReceiver(login, verifier, namespace, disposal); } /** Actual receipt-backed public source, not a replacement JWKS document. */ @@ -426,7 +436,8 @@ private static RedisScriptCatalog loginScriptCatalog() throws IOException { List.of( "/redis/scripts/account-game-session-delegation-pending-register.json", "/redis/scripts/account-game-session-delegation-activate-committed.json", - "/redis/scripts/account-game-session-delegation-authority-project-issuer.json")) { + "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", + "/redis/scripts/account-initial-gameplay-login-dispose.json")) { try (var input = AccountPlayerAdmissionSharedOwnerFixture.class.getResourceAsStream(resource)) { if (input == null) throw new IllegalStateException("Account LOGIN descriptor is absent"); diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 6478b840db..c2bd44fa92 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -190,8 +190,11 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture*.class") + include("net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture*.class") } from("src/main/resources") { + include("redis/lua/game-session-initial-context-cas.lua") + include("redis/scripts/game-session-initial-context-cas.json") include("redis/lua/game-session-issuer-bootstrap-partition-build.lua") include("redis/scripts/game-session-issuer-bootstrap-partition-build.json") include("redis/lua/game-session-issuer-binding-local-add.lua") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java new file mode 100644 index 0000000000..a7b3e63695 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java @@ -0,0 +1,385 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolVersion; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Actual original journal, PENDING, Account client and INSTALLED composition over borrowed physical + * stores. Credential delivery and external Redis qualification remain controlled. The caller must + * finish earlier users of the GS Redis principal before opening this fixture; no active sibling + * connections are reset. The decoded readback is historical evidence, not receiving custody, + * current token authority, gameplay admission or a production qualification provider. + */ +@SuppressWarnings("resource") +public final class InitialGameplayLoginPhysicalCompositionFixture implements AutoCloseable { + private static final String PRINCIPAL = InitialGameplayLoginRedisBinding.PRINCIPAL; + private static final String BINDING = "controlled-physical-initial-login-primary"; + private final InitialGameplayLoginCoordinationJournalRepository journal; + private final RedisClient writer; + private final List mutations = new ArrayList<>(); + private InitialGameplayLoginOwner.Outcome outcome; + private CanonicalGameplayLoginResult loginResult; + private InitialGameplayLoginContextState installedReadback; + private boolean closed; + + /** + * Transfers the mutable OTP buffer, but borrows the already migrated SQL owners, initialized + * actual Account client and test-owned AOF primary/replica. No listener or runtime bean is added. + */ + public static InitialGameplayLoginPhysicalCompositionFixture open( + DSLContext gs, + PlatformTransactionManager transactionManager, + String redisHost, + int redisPort, + CanonicalGameplayLoginAccountClient account, + String email, + String canonicalClientAddress, + char[] ownedOtp) { + Objects.requireNonNull(ownedOtp, "Owned credential buffer required"); + InitialGameplayLoginPhysicalCompositionFixture fixture = null; + try (var credentials = + new InitialGameplayLoginCredentialPresentation(email, canonicalClientAddress, ownedOtp)) { + fixture = new InitialGameplayLoginPhysicalCompositionFixture(gs, redisHost, redisPort); + fixture.receive(transactionManager, account, credentials); + assertThat(Arrays.equals(ownedOtp, new char[ownedOtp.length])).isTrue(); + return fixture; + } catch (RuntimeException | Error failure) { + if (fixture != null) { + try { + fixture.close(); + } catch (RuntimeException | Error cleanup) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } finally { + Arrays.fill(ownedOtp, '\0'); + } + } + + private InitialGameplayLoginPhysicalCompositionFixture( + DSLContext gs, String redisHost, int redisPort) { + journal = new InitialGameplayLoginCoordinationJournalRepository(gs); + String password = UUID.randomUUID().toString(); + configureOwnedPrincipal(redisHost, redisPort, password); + writer = redis(redisHost, redisPort, PRINCIPAL, password); + } + + private void receive( + PlatformTransactionManager transactionManager, + CanonicalGameplayLoginAccountClient account, + InitialGameplayLoginCredentialPresentation credentials) { + var contexts = + new InitialGameplayLoginContextRedisClient( + new InitialGameplayLoginRedisBinding( + BINDING, + this::observedConnection, + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 5_000)), + RedisScriptCatalog.fromContributions( + List.of(new InitialGameplayLoginRedisScriptContribution())), + new ControlledQualification()); + var cleanup = + new InitialGameplayLoginCleanupOwner( + journal, + new InitialGameplayLoginRedisAttemptClosure(contexts), + account, + transactionManager); + outcome = new InitialGameplayLoginOwner(contexts, cleanup, account).receive(credentials); + assertThat(outcome.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + loginResult = outcome.takePrivateResult().orElseThrow(); + assertThat(mutations).containsExactly("CREATE_PENDING", "INSTALL"); + installedReadback = physicalReadback(); + assertThat(installedReadback.state()) + .isEqualTo(InitialGameplayLoginContextState.State.INSTALLED); + assertThat(installedReadback.evidence()).isEqualTo(loginResult.evidence()); + var retained = journal.readCommitted(coordinates()).orElseThrow(); + assertThat(retained.abandoned()).isFalse(); + assertThat(retained.verifiedWitness()).contains(witness(installedReadback)); + assertThat(retained.frozenRetirementRequest()).isEmpty(); + byte[] compact = loginResult.compactJwtBytes(); + try { + assertThat(containsSequence(installedReadback.encode(), compact)).isFalse(); + } finally { + Arrays.fill(compact, (byte) 0); + } + } + + public InitialGameplayLoginAttemptCoordinates coordinates() { + return outcome.coordinates(); + } + + /** The actual owner outcome, retained for explicit pre-admission custody-loss cleanup. */ + public InitialGameplayLoginOwner.Outcome outcome() { + return outcome; + } + + /** Borrow the actual transferred result; the fixture retains its cleanup responsibility. */ + public CanonicalGameplayLoginResult loginResult() { + return loginResult; + } + + /** Historical physical installation evidence only; this does not authenticate current custody. */ + public InitialGameplayLoginContextState installedReadback() { + return installedReadback; + } + + /** + * Call before shutting down Account transport; known-token disposal uses that actual receiver. + */ + public InitialGameplayLoginCleanupOwner.CleanupObservation abandonOriginalAfterCustodyLoss() { + var observation = outcome.abandonOriginalAfterCustodyLoss(); + assertThat(physicalReadback().state()).isEqualTo(InitialGameplayLoginContextState.State.CLOSED); + var retained = journal.readCommitted(coordinates()).orElseThrow(); + assertThat(retained.abandoned()).isTrue(); + assertThat(retained.frozenRetirementRequest()).isPresent(); + assertThat(retained.frozenRetirementRequest().orElseThrow().getTokenWitness()) + .isEqualTo(witness(installedReadback)); + assertThatThrownBy(loginResult::compactJwtBytes).isInstanceOf(IllegalStateException.class); + return observation; + } + + private InitialGameplayLoginContextState physicalReadback() { + try (var connection = writer.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(PRINCIPAL); + byte[] key = key(coordinates()); + var decoded = InitialGameplayLoginContextState.decode(commands.get(key)); + assertThat(decoded.coordinates()).isEqualTo(coordinates()); + assertThat(commands.pttl(key)).isEqualTo(-1L); + return decoded; + } + } + + /** Every command still delegates to the real pinned physical connection. */ + @SuppressWarnings("unchecked") + private StatefulRedisConnection observedConnection() { + var connection = writer.connect(ByteArrayCodec.INSTANCE); + return (StatefulRedisConnection) + Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, args) -> { + if (!method.getName().equals("sync")) return invoke(connection, method, args); + var commands = connection.sync(); + return Proxy.newProxyInstance( + RedisCommands.class.getClassLoader(), + new Class[] {RedisCommands.class}, + (commandProxy, command, arguments) -> { + if (command.getName().equals("evalsha")) { + beforeMutation(commands, (byte[][]) arguments[2], (byte[][]) arguments[3]); + } + return invoke(commands, command, arguments); + }); + }); + } + + private void beforeMutation( + RedisCommands commands, byte[][] keys, byte[][] args) { + require(keys.length == 1 && args.length == 3); + String operation = new String(args[0], StandardCharsets.US_ASCII); + var desired = InitialGameplayLoginContextState.decode(args[2]); + var original = desired.coordinates(); + require(Arrays.equals(keys[0], key(original))); + var committed = journal.readCommitted(original).orElseThrow(); + require(original.expectedAttemptFence() == 1); + require(!original.requestId().equals(original.callerContextId())); + if ("CREATE_PENDING".equals(operation)) { + require(mutations.isEmpty()); + require(!committed.abandoned() && committed.verifiedWitness().isEmpty()); + // Observation only: the actual Lua absence check remains the create authority. + require(commands.get(keys[0]) == null); + } else if ("INSTALL".equals(operation)) { + require(mutations.equals(List.of("CREATE_PENDING"))); + require(!committed.abandoned()); + require(committed.verifiedWitness().filter(witness(desired)::equals).isPresent()); + var pending = InitialGameplayLoginContextState.decode(commands.get(keys[0])); + require(pending.coordinates().equals(original)); + require(pending.state() == InitialGameplayLoginContextState.State.PENDING); + } else { + require("CLOSE".equals(operation) && committed.abandoned()); + } + mutations.add(operation); + } + + private static InitialGameplayLoginTokenWitness witness(InitialGameplayLoginContextState state) { + var evidence = state.evidence(); + return InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(evidence.tokenJti().toString()) + .setTokenSha256(evidence.tokenSha256()) + .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) + .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) + .build(); + } + + private static Object invoke(Object target, Method method, Object[] arguments) throws Throwable { + try { + return method.invoke(target, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + } + + private static void configureOwnedPrincipal(String host, int port, String password) { + var administrator = redis(host, port, null, null); + try (var connection = administrator.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + require( + commands + .clientList() + .lines() + .noneMatch(line -> line.contains(" user=" + PRINCIPAL + " "))); + commands.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.PEXPIRETIME)); + commands.dispatch( + CommandType.ACL, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add("SETUSER").add(PRINCIPAL).add("+waitaof")); + } finally { + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private static RedisClient redis(String host, int port, String username, String password) { + var builder = RedisURI.Builder.redis(host, port); + if (username != null) builder.withAuthentication(username, password); + var uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(10)); + var client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + return client; + } + + private static byte[] key(InitialGameplayLoginAttemptCoordinates coordinates) { + return InitialGameplayLoginContextRedisKeys.contextKey(coordinates.callerContextId()) + .getBytes(StandardCharsets.US_ASCII); + } + + private static boolean containsSequence(byte[] haystack, byte[] needle) { + for (int offset = 0; offset <= haystack.length - needle.length; offset++) { + if (Arrays.equals(haystack, offset, offset + needle.length, needle, 0, needle.length)) { + return true; + } + } + return false; + } + + private static void require(boolean condition) { + if (!condition) + throw new IllegalStateException("Physical initial LOGIN fixture precondition failed"); + } + + /** Stipulated test authority only, never a production recovery or transport-custody producer. */ + private static final class ControlledQualification + implements InitialGameplayLoginCoordinationQualification { + @Override + public Optional acquire(String scope, String binding) { + require(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE.equals(scope)); + require(BINDING.equals(binding)); + return Optional.of( + new Lease() { + private boolean closed; + + @Override + public String scope() { + return scope; + } + + @Override + public String protectedBindingId() { + return binding; + } + + @Override + public long fence() { + return 37; + } + + @Override + public void requireCurrent() { + require(!closed); + } + + @Override + public void close() { + closed = true; + } + }); + } + } + + /** + * Ends pre-admission private custody before closing owned Redis clients. Retained SQL rows and + * Redis markers stay with the enclosing disposable physical fixture, without a retention bypass. + */ + @Override + public void close() { + if (closed) return; + closed = true; + try { + if (outcome != null + && outcome.status() == InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING + && outcome.custodyLossCleanup().isEmpty()) { + outcome.abandonOriginalAfterCustodyLoss(); + } + } finally { + if (loginResult != null) loginResult.close(); + if (outcome != null) outcome.close(); + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 9da1ecfd40..1d6c14c759 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -64,14 +64,12 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture; -import net.firedevops.firemud.accountservice.service.session.AccountPlayerAdmissionSharedOwnerFixture; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionAcquisitionGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionSettlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionSettlementService; @@ -3452,22 +3450,8 @@ private static void composeActualEntityWorldRegionPrerequisite( try { var worldEndpoints = new ServiceEndpointsProperties(); worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); - // Authenticate after the earlier password/authority mutation has settled. The - // creation tuple is shared by Account, World and GS; the caller is still controlled. - var loginOwner = - new AccountPlayerAdmissionSharedOwnerFixture( - account, proofDirectory.resolve("shared-login")); - var loginRequest = - loginOwner.loginRequest( - UUID.randomUUID(), - new GameplayCredentialSourceContext( - UUID.randomUUID(), "192.0.2.42", "direct-text")); - var loginResult = - loginOwner.authenticate( - loginRequest, "spiffe://firemud/ns/firemud/sa/game-session-service"); - loginOwner.assertCommittedNonAdmittingLogin(loginResult); - assertThat(loginResult.accountId()).isEqualTo(accountUuid); - assertThat(loginOwner.creationEvidence()).isEqualTo(account.creationEvidence()); + // The earlier generic password-write proof deliberately leaves creator LOGIN + // currentness unavailable. The later composition uses a separate fresh player. var initialLocationClient = new CanonicalInitialPlayerLocationClient( worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); @@ -3578,6 +3562,9 @@ private static void composeActualEntityWorldRegionPrerequisite( WorldPublishedAdmissionSourceComposition.exercise( proofDirectory, gs.dsl(), + gs.manager(), + REDIS.getHost(), + REDIS.getMappedPort(6379), currentTarget, accountUuid, account, diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java index f1dfba1329..b92316a776 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -34,16 +34,16 @@ import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginPhysicalCompositionFixture; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import net.firedevops.firemud.test.LoopbackMtlsTestPki; /** * Actual LOGIN and PLAYER_ADMISSION producer/consumer with a genuine absent player and shared - * Account/GS/World sources, followed by genuine owner-local first JOIN and positive source read. - * DEMO policy, caller coordinates, PKI and local custody callbacks are controlled. No public - * ingress, installed custody, World hold across JOIN, runtime activation or PLAY is proved. + * Account/GS/World sources and physical GS journal/PENDING/INSTALLED state, followed by actual + * first JOIN, positive source read and known-token retirement. DEMO policy, caller coordinates, + * PKI, reset/promotion qualification and receiving custody remain controlled. No public ingress, + * protected receiving custody, World hold across JOIN, runtime activation or PLAY is proved. */ final class WorldPlayerAdmissionEntitlementComposition { private WorldPlayerAdmissionEntitlementComposition() {} @@ -52,7 +52,11 @@ static void exercise( Path root, AccountControlUiOriginalOrderFixture original, CanonicalGameplayAdmissionDecisionReadClient targets, - CanonicalPlayableTarget target) + CanonicalPlayableTarget target, + org.jooq.DSLContext gs, + org.springframework.transaction.PlatformTransactionManager gsTransactions, + String redisHost, + int redisPort) throws Exception { var clock = Clock.systemUTC(); String namespace = target.targetNamespace(); @@ -131,13 +135,23 @@ static void exercise( entitlementEndpoints, tls, channels, namespace, clock)) { loginClient.initialize(); entitlementClient.init(); - var wireRequest = - loginOwner.wireLoginRequest( + // This request is only a controlled credential source. GS allocates real coordinates. + var credentialSource = + loginOwner.loginRequest( UUID.randomUUID(), new GameplayCredentialSourceContext( UUID.randomUUID(), "192.0.2.42", "trusted_tcp_proxy")); - // Controlled original custody; the returned credential and Account currentness are real. - try (var login = loginClient.authenticate(wireRequest, () -> true)) { + try (var physicalLogin = + InitialGameplayLoginPhysicalCompositionFixture.open( + gs, + gsTransactions, + redisHost, + redisPort, + loginClient, + credentialSource.email(), + "192.0.2.42", + credentialSource.credential().toCharArray())) { + var login = physicalLogin.loginResult(); var evidence = login.evidence(); loginOwner.assertCommittedNonAdmittingLogin( evidence.requestId(), @@ -178,14 +192,12 @@ static void exercise( .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) .build(), clock); - var coordinates = - new InitialGameplayLoginAttemptCoordinates( - evidence.requestId(), evidence.callerContextId(), 1L); - // This encodes a desired value only. No Redis installed-custody proof is claimed. + var coordinates = physicalLogin.coordinates(); + // Physical INSTALLED readback is real; protected receiving custody remains controlled. var lobby = new DirectTextAuthenticatedLobbyScope( UUID.randomUUID(), - InitialGameplayLoginContextState.installed(coordinates, login), + physicalLogin.installedReadback(), transport, target, issued); @@ -207,6 +219,15 @@ static void exercise( entitlementClient.read( lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) .isInstanceOf(RuntimeException.class); + assertThat(physicalLogin.abandonOriginalAfterCustodyLoss().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner + .Status.ACCOUNT_RETIRED); + assertThatThrownBy( + () -> + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) + .isInstanceOf(RuntimeException.class); } } } finally { diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java index 3cf1298364..a1e9ed5ffb 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -41,7 +41,8 @@ * Real GS OPEN/current publication and World ACTIVE reads over authenticated sockets, followed by * actual Account LOGIN, absent-player entitlement, owner-local first JOIN and positive source * reread. Game Design publication, DEMO policy, PKI, caller coordinates and custody callbacks are - * controlled. No public ingress, World hold across JOIN, installed custody or activation is proved. + * controlled. No public ingress, World hold across JOIN, protected receiving custody or activation + * is proved. */ final class WorldPublishedAdmissionSourceComposition { private WorldPublishedAdmissionSourceComposition() {} @@ -49,6 +50,9 @@ private WorldPublishedAdmissionSourceComposition() {} static void exercise( Path root, DSLContext gs, + org.springframework.transaction.PlatformTransactionManager gsTransactions, + String redisHost, + int redisPort, CanonicalPlayableTarget target, UUID account, net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture @@ -199,7 +203,14 @@ public void listPublishedRealmEntryPolicies( assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) .isInstanceOf(RuntimeException.class); WorldPlayerAdmissionEntitlementComposition.exercise( - root, originalAccount, accountClient, target); + root, + originalAccount, + accountClient, + target, + gs, + gsTransactions, + redisHost, + redisPort); } } finally { stop(receiver); From ff67f1c3b0542b1ff129e2812fb96425a2810406 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 07:14:37 +1300 Subject: [PATCH 13/66] fix: order tenant tag locks before issuer barrier claims --- ...alGameplayTenantGameplayTagRepository.java | 4 + ...ssionBarrierRepositoryIntegrationTest.java | 89 ++++++++++++++----- 2 files changed, 71 insertions(+), 22 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 5e982717e8..a2f8a8312a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -48,6 +48,9 @@ public Assignment assignmentForTransition(UUID transitionId) { return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); + // Issuer barrier claims take this clock before locking the mapping and source rows. + // Keep the same order so a retained claim cannot deadlock with tag resolution. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); BindingTarget source = loadBindingTarget(transaction, transitionId); requireTenantClaim(transaction, source.tenantId()); return resolveMapping( @@ -242,6 +245,7 @@ Assignment assignmentForTransitionWithCandidate( return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); BindingTarget source = loadBindingTarget(transaction, transitionId); requireTenantClaim(transaction, source.tenantId()); return resolveMapping(transaction, source, candidateVersion, candidateTag); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index 9396137ad6..b133218bff 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -46,8 +46,11 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -230,36 +233,78 @@ void concurrentClaimsOfRetainedPreparedReadsHaveOnlyOneFirstCreateWinner() throw UUID operationId = state.fixture().originalOperationId(); var first = state.repository().readPreparedInitializer(operationId); var second = state.repository().readPreparedInitializer(operationId); - CountDownLatch start = new CountDownLatch(1); + assertThat(first.assignment()).isNotNull(); + assertThat(second.assignment()).isNull(); + CountDownLatch retainedMappingLocked = new CountDownLatch(1); + CountDownLatch assignmentLockAttempted = new CountDownLatch(1); + var retainedClaimListener = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("FROM game_session_canonical_tenant_gameplay_tag") + && sql.endsWith("FOR SHARE")) { + retainedMappingLocked.countDown(); + try { + if (!assignmentLockAttempted.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled assignment lock attempt timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled claim gate interrupted", interrupted); + } + } + } + }; + var assignmentListener = + new DefaultExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.endsWith("FOR UPDATE") + && (sql.contains("FROM game_session_canonical_binding_inventory_clock") + || sql.contains("FROM game_session_canonical_tenant_gameplay_tag"))) { + // With the owner lock order this waits on the clock before taking source locks. + // Without it, this reaches the tag only after locking transition/inventory, while + // the retained claim owns the tag and still needs the transition: a real deadlock. + assignmentLockAttempted.countDown(); + } + } + }; + DSLContext dsl = state.fixture().dsl(); + var retainedDsl = + DSL.using( + dsl.configuration().derive(new DefaultExecuteListenerProvider(retainedClaimListener))); + var assignmentDsl = + DSL.using( + dsl.configuration().derive(new DefaultExecuteListenerProvider(assignmentListener))); + String namespace = state.fixture().target().targetNamespace(); + var retainedRepository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + retainedDsl, + new CanonicalGameplayTenantGameplayTagRepository(dsl, namespace, 1), + state.sourceReader()); + var assignmentRepository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + dsl, + new CanonicalGameplayTenantGameplayTagRepository(assignmentDsl, namespace, 1), + state.sourceReader()); ExecutorService executor = Executors.newFixedThreadPool(2); try { - var firstClaim = - executor.submit( - () -> { - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Controlled claim start timed out"); - } - return state.repository().claimFirstCreatePermit(first); - }); - var secondClaim = - executor.submit( - () -> { - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Controlled claim start timed out"); - } - return state.repository().claimFirstCreatePermit(second); - }); - start.countDown(); - assertThat( - List.of(firstClaim.get(10, TimeUnit.SECONDS), secondClaim.get(10, TimeUnit.SECONDS))) - .containsExactlyInAnyOrder(true, false); + var secondClaim = executor.submit(() -> retainedRepository.claimFirstCreatePermit(second)); + assertThat(retainedMappingLocked.await(10, TimeUnit.SECONDS)).isTrue(); + var firstClaim = executor.submit(() -> assignmentRepository.claimFirstCreatePermit(first)); + assertThat(secondClaim.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(firstClaim.get(10, TimeUnit.SECONDS)).isFalse(); assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) .isInstanceOf(IllegalStateException.class); assertThat(countReceipt(state, operationId)).isZero(); assertThat(administratorCommands.exists(bytes(first.key()))).isZero(); } finally { - start.countDown(); + assignmentLockAttempted.countDown(); executor.shutdownNow(); } } From 8b6b65c0edd08d7523b4e2dd7f2d208d7d102814 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 07:41:40 +1300 Subject: [PATCH 14/66] test: localize physical login cleanup failures without secret diagnostics --- ...meplayLoginPhysicalCompositionFixture.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java index a7b3e63695..0c778a8049 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java @@ -51,6 +51,7 @@ public final class InitialGameplayLoginPhysicalCompositionFixture implements Aut private final InitialGameplayLoginCoordinationJournalRepository journal; private final RedisClient writer; private final List mutations = new ArrayList<>(); + private final List journalObservations = new ArrayList<>(); private InitialGameplayLoginOwner.Outcome outcome; private CanonicalGameplayLoginResult loginResult; private InitialGameplayLoginContextState installedReadback; @@ -93,7 +94,28 @@ public static InitialGameplayLoginPhysicalCompositionFixture open( private InitialGameplayLoginPhysicalCompositionFixture( DSLContext gs, String redisHost, int redisPort) { - journal = new InitialGameplayLoginCoordinationJournalRepository(gs); + var actualJournal = new InitialGameplayLoginCoordinationJournalRepository(gs); + // Observation only: every method delegates to the unchanged real SQL owner. + journal = + org.mockito.Mockito.mock( + InitialGameplayLoginCoordinationJournalRepository.class, + invocation -> { + String operation = invocation.getMethod().getName(); + try { + Object result = + invoke(actualJournal, invocation.getMethod(), invocation.getArguments()); + journalObservations.add(operation + ":OK"); + return result; + } catch (Throwable failure) { + String sqlState = + failure instanceof org.jooq.exception.DataAccessException sql + ? sql.sqlState() + : "none"; + journalObservations.add( + operation + ":" + failure.getClass().getSimpleName() + ":" + sqlState); + throw failure; + } + }); String password = UUID.randomUUID().toString(); configureOwnedPrincipal(redisHost, redisPort, password); writer = redis(redisHost, redisPort, PRINCIPAL, password); @@ -120,6 +142,9 @@ private void receive( transactionManager); outcome = new InitialGameplayLoginOwner(contexts, cleanup, account).receive(credentials); assertThat(outcome.status()) + .as( + "Initial LOGIN failureCode=%s journal=%s mutations=%s", + outcome.failureCode(), journalObservations, mutations) .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); loginResult = outcome.takePrivateResult().orElseThrow(); assertThat(mutations).containsExactly("CREATE_PENDING", "INSTALL"); From 4cdd00790a488d78ab9aec019e4982c300a18b5c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 08:10:15 +1300 Subject: [PATCH 15/66] test: use durable Account fixture and trace physical login stages --- ...ountPlayerAdmissionSharedOwnerFixture.java | 147 ++++++++++++------ ...ationOwnerCompositionCrossServiceTest.java | 13 +- ...PlayerAdmissionEntitlementComposition.java | 5 + 3 files changed, 119 insertions(+), 46 deletions(-) diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java index 8d9b53e240..ad28fb69a8 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -16,6 +17,7 @@ import java.util.List; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import javax.crypto.spec.SecretKeySpec; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; @@ -77,6 +79,7 @@ public final class AccountPlayerAdmissionSharedOwnerFixture { private final AccountGameplayPrimaryCredentialVerifier verifier; private final AccountGameplayDelegationCommittedIssuanceOwner committedOwner; private final AccountInitialGameplayLoginDisposalOwner disposal; + private final List ownerObservations = new CopyOnWriteArrayList<>(); private final String otp = "shared-login-" + UUID.randomUUID(); public AccountPlayerAdmissionSharedOwnerFixture( @@ -130,9 +133,11 @@ private AccountPlayerAdmissionSharedOwnerFixture( issuanceProxy.addAdvice( new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); issuance = - (AccountGameplayDelegationIssuanceRepository) - issuanceProxy.getProxy( - AccountGameplayDelegationIssuanceRepository.class.getClassLoader()); + observed( + AccountGameplayDelegationIssuanceRepository.class, + (AccountGameplayDelegationIssuanceRepository) + issuanceProxy.getProxy( + AccountGameplayDelegationIssuanceRepository.class.getClassLoader())); var cryptography = new AccountResponseEnvelopeCryptography( new AccountResponseEnvelopeKeyring(writeResponseKeyring(temporary).toString())); @@ -141,60 +146,112 @@ private AccountPlayerAdmissionSharedOwnerFixture( sources.dsl, authoritySources, bundles, issuance, cryptography); var lifecycle = original.signerFixture; var signer = - new AccountGameplayDelegationSigner( - issuance, - lifecycle.desired, - lifecycle.trust, - lifecycle.api, - original.publicSource, - new AccountGameplayDelegationResponseEnvelopeService(envelopes), - sources.manager, - clock, - lifecycle.privateRoot, - Path.of("current.key"), - lifecycle.publicRoot, - Path.of("jwks.json")); + observed( + AccountGameplayDelegationSigner.class, + new AccountGameplayDelegationSigner( + issuance, + lifecycle.desired, + lifecycle.trust, + lifecycle.api, + original.publicSource, + new AccountGameplayDelegationResponseEnvelopeService(envelopes), + sources.manager, + clock, + lifecycle.privateRoot, + Path.of("current.key"), + lifecycle.publicRoot, + Path.of("jwks.json"))); var redis = - new AccountGameplayDelegationRedisClient( - connections, - loginScriptCatalog(), - new AcknowledgementRequirements(1, 1, 5_000), - clock, - REGISTRY_BYTES, - AccountPlayerAdmissionSharedOwnerFixture.class.getClassLoader()); + observed( + AccountGameplayDelegationRedisClient.class, + new AccountGameplayDelegationRedisClient( + connections, + loginScriptCatalog(), + new AcknowledgementRequirements(1, 1, 5_000), + clock, + REGISTRY_BYTES, + AccountPlayerAdmissionSharedOwnerFixture.class.getClassLoader())); projection = - new AccountGameplayDelegationAuthorityProjection(authoritySources, sources.manager, redis); + observed( + AccountGameplayDelegationAuthorityProjection.class, + new AccountGameplayDelegationAuthorityProjection( + authoritySources, sources.manager, redis)); var registry = - new AccountGameplayDelegationTokenRegistry( - issuance, sources.manager, redis, clock, REGISTRY_BYTES, REGISTRY_CLEANUP_MILLIS); + observed( + AccountGameplayDelegationTokenRegistry.class, + new AccountGameplayDelegationTokenRegistry( + issuance, sources.manager, redis, clock, REGISTRY_BYTES, REGISTRY_CLEANUP_MILLIS)); disposal = - new AccountInitialGameplayLoginDisposalOwner( - new AccountInitialGameplayLoginDisposalRepository(sources.dsl), - registry, - sources.manager); + observed( + AccountInitialGameplayLoginDisposalOwner.class, + new AccountInitialGameplayLoginDisposalOwner( + observed( + AccountInitialGameplayLoginDisposalRepository.class, + new AccountInitialGameplayLoginDisposalRepository(sources.dsl)), + registry, + sources.manager)); var commit = - new AccountGameplayDelegationIssuanceCommitService( - signer, registry, projection, issuance, sources.manager, clock); + observed( + AccountGameplayDelegationIssuanceCommitService.class, + new AccountGameplayDelegationIssuanceCommitService( + signer, registry, projection, issuance, sources.manager, clock)); committedOwner = - new AccountGameplayDelegationCommittedIssuanceOwner( - issuance, signer, registry, sources.manager, clock); + observed( + AccountGameplayDelegationCommittedIssuanceOwner.class, + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signer, registry, sources.manager, clock)); var recovery = - new AccountGameplayDelegationResponseRecoveryOwner( - envelopes, committedOwner, sources.manager); - verifier = new AccountGameplayPrimaryCredentialVerifier(sources.primary); + observed( + AccountGameplayDelegationResponseRecoveryOwner.class, + new AccountGameplayDelegationResponseRecoveryOwner( + envelopes, committedOwner, sources.manager)); + verifier = + observed( + AccountGameplayPrimaryCredentialVerifier.class, + new AccountGameplayPrimaryCredentialVerifier(sources.primary)); login = - new AccountGameplayCanonicalLoginOwner( - sources.accounts, - issuance, - digestKeys(clock), - commit, - recovery, - sources.manager, - clock); + observed( + AccountGameplayCanonicalLoginOwner.class, + new AccountGameplayCanonicalLoginOwner( + sources.accounts, + issuance, + digestKeys(clock), + commit, + recovery, + sources.manager, + clock)); // Control-UI consumed the original challenge. Never resurrect or reuse that consumed row. sources.installGlobalOtp(account, otp); } + /** Bounded stage names only; no invocation arguments, results, SQL or token material. */ + public List ownerObservations() { + return List.copyOf(ownerObservations); + } + + private T observed(Class type, T actual) { + return org.mockito.Mockito.mock( + type, + invocation -> { + String operation = type.getSimpleName() + "." + invocation.getMethod().getName(); + ownerObservations.add(operation + ":ENTER"); + try { + Object result = invocation.getMethod().invoke(actual, invocation.getArguments()); + ownerObservations.add(operation + ":OK"); + return result; + } catch (InvocationTargetException wrapped) { + Throwable failure = wrapped.getCause(); + String sqlState = + failure instanceof org.jooq.exception.DataAccessException sql + ? sql.sqlState() + : "none"; + ownerObservations.add( + operation + ":" + failure.getClass().getSimpleName() + ":" + sqlState); + throw failure; + } + }); + } + public UUID accountId() { return account.getAccountUuid(); } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 1d6c14c759..7f4e0d1c26 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -305,7 +305,9 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @Container static final PostgreSQLContainer ACCOUNT = - new PostgreSQLContainer<>(TestContainerImages.postgres()); + // Account's exact-original LOGIN disposal refuses nondurable PostgreSQL settings. + new PostgreSQLContainer<>(TestContainerImages.postgres()) + .withCommand("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); @Container static final GenericContainer REDIS = @@ -602,6 +604,15 @@ private void compose( var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( account, proofDirectory.resolve("issuer"), NAMESPACE); + var accountDurability = + issuer + .sourceDsl() + .fetchSingle( + "SELECT pg_is_in_recovery() AS recovery, current_setting('fsync') AS fsync," + + " current_setting('synchronous_commit') AS commit_mode"); + assertThat(accountDurability.get("recovery", Boolean.class)).isFalse(); + assertThat(accountDurability.get("fsync", String.class)).isEqualTo("on"); + assertThat(accountDurability.get("commit_mode", String.class)).isEqualTo("on"); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java index b92316a776..93461ec33c 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -228,6 +228,11 @@ static void exercise( entitlementClient.read( lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) .isInstanceOf(RuntimeException.class); + } catch (RuntimeException | Error failure) { + failure.addSuppressed( + new AssertionError( + "Account LOGIN owner stages: " + loginOwner.ownerObservations())); + throw failure; } } } finally { From 2e2a7d3d7cd07b1905a202a25d840a0dc6df347e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 08:33:28 +1300 Subject: [PATCH 16/66] test: export installed Account Redis catalog in proof jar --- services/account-service/build.gradle.kts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 0c89f71487..a561467fa3 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -204,6 +204,9 @@ val accountOriginalOrderProofJar by tasks.registering(Jar::class) { include("redis/scripts/account-game-session-delegation-authority-project-issuer.json") include("redis/scripts/account-initial-gameplay-login-dispose.json") include("redis/scripts/account-generation-projection-cas.json") + include("redis/scripts/account-selected-tenant-generation-projection.json") + include("redis/scripts/account-selected-membership-generation-projection.json") + include("META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution") } } From 5673456f43151791fa744b6740f97c547c05a8e8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 10:41:10 +1300 Subject: [PATCH 17/66] Keep public facade review bounded; retain admission composition in successor --- .../account-service/api-contracts.md | 4 +- .../player-access-and-session.md | 12 +- .../player_admission_entitlement_read.proto | 35 - ...ayerAdmissionEntitlementWorkloadGuard.java | 76 -- ...ccountPlayerAdmissionEntitlementOwner.java | 623 ------------ ...PlayerAdmissionEntitlementGrpcService.java | 120 --- ...CurrentSourcesPostgresIntegrationTest.java | 100 +- ...mittedLoginCompositionIntegrationTest.java | 344 ------- ...titlementOwnerPostgresIntegrationTest.java | 718 ------------- ...AdmissionEntitlementWorkloadGuardTest.java | 117 --- ...ntPlayerAdmissionEntitlementOwnerTest.java | 941 ------------------ ...erAdmissionEntitlementGrpcServiceTest.java | 47 - .../AccountControlUiOriginalOrderFixture.java | 76 +- .../AccountControlUiOwnerSourcesFixture.java | 71 +- ...ayerAdmissionSharedEntitlementFixture.java | 559 ----------- ...ountPlayerAdmissionSharedOwnerFixture.java | 523 ---------- ...imePlayerAdmissionEntitlementEvidence.java | 588 ----------- ...layerAdmissionEntitlementEvidenceTest.java | 298 ------ ...mePlayerAdmissionEntitlementGrpcCodec.java | 161 --- ...ayerAdmissionEntitlementGrpcCodecTest.java | 279 ------ .../game-session-service/build.gradle.kts | 4 - ...countPlayerAdmissionEntitlementClient.java | 393 -------- ...dmissionActualOwnerCompositionFixture.java | 51 - ...meplayLoginPhysicalCompositionFixture.java | 410 -------- ...yerAdmissionEntitlementClientMtlsTest.java | 783 --------------- ...ationOwnerCompositionCrossServiceTest.java | 49 +- ...PlayerAdmissionEntitlementComposition.java | 250 ----- ...ldPublishedAdmissionSourceComposition.java | 247 ----- 28 files changed, 38 insertions(+), 7841 deletions(-) delete mode 100644 protos/account/v1/player_admission_entitlement_read.proto delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java delete mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java delete mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java delete mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java delete mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java delete mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java delete mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java delete mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java delete mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java delete mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java delete mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d669cf1e9d..6e6c3fa494 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -460,9 +460,9 @@ The canonical membership, entitlement response shape, freshness, and sequence co ### Private player-admission entitlement read -The distinct [PLAYER_ADMISSION protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto) carries the complete retained canonical target selector, Account-issued connect scope and explicit initial Game Session Account-delegation credential. The manually composed Account receiver authenticates the exact same-namespace Game Session workload before decoding, then its existing caller/current-source owners verify the credential and capture current Account membership/entitlement and protected target evidence. Ambient bearer or caller-supplied workload context cannot replace transport identity. The response echoes the closed selectors and carries canonical PLAYER_ADMISSION evidence without echoing the credential; absent/unavailable authority never becomes a successful empty response or demo fallback. +The distinct [PLAYER_ADMISSION protobuf](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/protos/account/v1/player_admission_entitlement_read.proto) carries the complete retained canonical target selector, Account-issued connect scope and explicit initial Game Session Account-delegation credential. The manually composed Account receiver authenticates the exact same-namespace Game Session workload before decoding, then its existing caller/current-source owners verify the credential and capture current Account membership/entitlement and protected target evidence. Ambient bearer or caller-supplied workload context cannot replace transport identity. The response echoes the closed selectors and carries canonical PLAYER_ADMISSION evidence without echoing the credential; absent/unavailable authority never becomes a successful empty response or demo fallback. -The [closed wire codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns the executable size/deadline bounds and exact comparison rules. `scopeDigest` preserves the exact retained V2 `sha256:`-prefixed digest; token/registry SHA-256 fields retain their distinct raw-hex representation. This protected read supplies evidence rather than membership repair, actor selection, capacity or gameplay admission. The receiver and Game Session client remain explicitly composed and unregistered; canonical runtime cutover and complete source protection remain unfinished in the [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). +The [closed wire codec](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns the executable size/deadline bounds and exact comparison rules. `scopeDigest` preserves the exact retained V2 `sha256:`-prefixed digest; token/registry SHA-256 fields retain their distinct raw-hex representation. This protected read supplies evidence rather than membership repair, actor selection, capacity or gameplay admission. The receiver and Game Session client remain explicitly composed and unregistered; canonical runtime cutover and complete source protection remain unfinished in the [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). ### Private tenant-operation entitlement read 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 b9ad4d802d..77f693dbd8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,11 +8,15 @@ This is a non-normative implementation tracker for player access and session. Ca Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. +### Receiving review boundaries + +PR #3390 owns the canonical public UUID facade, JOIN and persisted-actor discovery, including the issuer lock-order correction and regression. The separate PLAYER_ADMISSION entitlement protocol, Account owner and receiver, Game Session client, and shared actual-owner LOGIN/World composition proof are retained in the existing successor PR #3403. Links below identify the retained source comparison where those files are absent from the reduced public-facade boundary. This relocation preserves the implementations and their original proof attribution; it grants neither canonical PLAY success nor production registration, custody, admission or activation. + ### Controlled player-admission transport composition -The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. +The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. -A further prepared [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java) replaces the LOGIN caller/currentness doubles with real committed issuance, response recovery, signature/profile verification and current Account owner reads. It uses a current persisted connect scope and physical Redis/PostgreSQL fixtures before calling the same unregistered mTLS receiver and Game Session consumer. Test signing custody, initial response delivery and protected published Game Session/World inputs remain controlled. The additional case also refuses a real Account token-fence revocation despite retained signature bytes and local custody. Compilation, enabled integration Checkstyle/SpotBugs, formatting and documentation checks pass. All five selected PostgreSQL cases, including this additional case, are skipped locally because Docker is unavailable; physical execution remains pending. No default PLAY route or activation is enabled. +A further prepared [committed-LOGIN composition](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java) replaces the LOGIN caller/currentness doubles with real committed issuance, response recovery, signature/profile verification and current Account owner reads. It uses a current persisted connect scope and physical Redis/PostgreSQL fixtures before calling the same unregistered mTLS receiver and Game Session consumer. Test signing custody, initial response delivery and protected published Game Session/World inputs remain controlled. The additional case also refuses a real Account token-fence revocation despite retained signature bytes and local custody. Compilation, enabled integration Checkstyle/SpotBugs, formatting and documentation checks pass. All five selected PostgreSQL cases, including this additional case, are skipped locally because Docker is unavailable; physical execution remains pending. No default PLAY route or activation is enabled. ### Canonical billing and retention receiving @@ -238,7 +242,7 @@ On Gameplay receiving source `c2f04d797179710e81df08033b16d4f596997e1e`, the sam The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. -The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. +The existing [World original-owner composition](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. ### Original creator validity at the callback boundary @@ -553,7 +557,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.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` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `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) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [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); [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); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [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); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `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); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_UNAVAILABLE` before entitlement reads, cached replay or token issuance; older positive-issuance tests are historical. 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 shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [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); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.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 [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | diff --git a/protos/account/v1/player_admission_entitlement_read.proto b/protos/account/v1/player_admission_entitlement_read.proto deleted file mode 100644 index ee5d174bb6..0000000000 --- a/protos/account/v1/player_admission_entitlement_read.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; - -package account.v1; - -import "game-session/v1/canonical_gameplay_admission_decision_read.proto"; - -option java_package = "net.firedevops.firemud.account.v1"; -option java_multiple_files = true; - -// Manually composed Account read for exact same-namespace Game Session over workload mTLS. -// This point-in-time PLAYER_ADMISSION value supplies neither capacity nor a later World hold. -service AccountPlayerAdmissionEntitlementReadService { - rpc ReadPlayerAdmissionEntitlement(ReadPlayerAdmissionEntitlementRequest) - returns (ReadPlayerAdmissionEntitlementResponse); -} - -// Comparison selectors only. Account verifies the credential subject and retained scope, and -// selects the current paid/demo source itself. Repeated members each require exactly one value. -message PlayerAdmissionEntitlementReadSelectors { - repeated uint32 schema_version = 1; - repeated game_session.v1.ResolvePublishedRealmAdmissionTargetRequest target = 2; - repeated string connect_scope_id = 3; -} - -// Credential travels only on this exact trusted mTLS method and must never be logged or persisted. -message ReadPlayerAdmissionEntitlementRequest { - repeated PlayerAdmissionEntitlementReadSelectors selectors = 1; - repeated string initial_login_jwt = 2; -} - -// Echo only selectors, never the presented credential. Evidence is exact bounded RFC 8785 UTF-8. -message ReadPlayerAdmissionEntitlementResponse { - repeated PlayerAdmissionEntitlementReadSelectors request = 1; - repeated bytes canonical_evidence = 2; -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java deleted file mode 100644 index d4839ed5e5..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.firedevops.firemud.accountservice.security; - -import io.grpc.Context; -import io.grpc.Contexts; -import io.grpc.Grpc; -import io.grpc.Metadata; -import io.grpc.ServerCall; -import io.grpc.ServerCallHandler; -import io.grpc.ServerInterceptor; -import io.grpc.Status; -import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.SessionContext; - -/** - * Exact method/Game Session gate deriving its private assertion from transport TLS, never caller - * context. - */ -public final class AccountPlayerAdmissionEntitlementWorkloadGuard implements ServerInterceptor { - private final Context.Key authenticatedCaller = - Context.key("player-admission-game-session-peer"); - private final String expectedWorkload; - - public AccountPlayerAdmissionEntitlementWorkloadGuard(String namespace) { - if (!GrpcPeerIdentity.isValidNamespace(namespace)) { - throw new IllegalArgumentException("Canonical Account workload namespace required"); - } - expectedWorkload = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; - } - - /** Only this guard's TLS interception can supply the private method-authorized assertion. */ - public String requireAuthenticatedGameSessionCaller() { - if (!expectedWorkload.equals(authenticatedCaller.get()) || hasSessionContext()) { - throw Status.UNAUTHENTICATED - .withDescription("Protected Game Session workload call required") - .asRuntimeException(); - } - return expectedWorkload; - } - - @Override - public ServerCall.Listener interceptCall( - ServerCall call, Metadata headers, ServerCallHandler next) { - var peer = - GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); - if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); - if (!expectedWorkload.equals(peer.orElseThrow().uri()) - || hasSessionContext() - || !AccountPlayerAdmissionEntitlementReadServiceGrpc - .getReadPlayerAdmissionEntitlementMethod() - .getFullMethodName() - .equals(call.getMethodDescriptor().getFullMethodName())) { - return deny(call, Status.PERMISSION_DENIED); - } - return Contexts.interceptCall( - Context.current().withValue(authenticatedCaller, peer.orElseThrow().uri()), - call, - headers, - next); - } - - private static boolean hasSessionContext() { - return SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService() - || SessionContext.getServiceName() != null - || SessionContext.getServiceInstanceId() != null; - } - - private static ServerCall.Listener deny( - ServerCall call, Status status) { - call.close( - status.withDescription("Exact protected Game Session entitlement method required"), - new Metadata()); - return new ServerCall.Listener<>() {}; - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java deleted file mode 100644 index fc705d2d1b..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ /dev/null @@ -1,623 +0,0 @@ -package net.firedevops.firemud.accountservice.service; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.sql.Connection; -import java.time.Clock; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.function.Supplier; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; -import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.common.security.SessionContext; -import org.jooq.DSLContext; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Unregistered Account owner for PUBLIC_PRODUCTION SHARED PRESEEDED player entitlement evidence. - * JWT/registry, Stripe and protected Game Session/World reads run outside SQL. A final - * Account-first writable SERIALIZABLE transaction rereads caller issuance, membership (including - * explicit absence), exact persisted scope and paid/demo currentness before constructing the - * canonical value. No value escapes a failed commit. All repositories and the DSL must share the - * transaction manager. - * - *

The protected target is a point-in-time source read, not a World lock through this transaction - * or later mutation. This grants no capacity or admission. Request workload remains a trusted - * method-authorized transport assertion; parsing it does not authenticate it. No bean, public RPC, - * issuer or activation is supplied. Private/playtest and PLAYER_CREATED are unsupported. - */ -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators are private Account owner-source components.") -public final class AccountPlayerAdmissionEntitlementOwner { - private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; - private final DSLContext dsl; - private final AccountRepository accounts; - private final AccountGameplayAdmissionCallerVerifier callers; - private final AccountGameplayDelegationIssuanceRepository issuances; - private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; - private final AccountConnectScopeRepository scopes; - private final AccountHostingSubscriptionLifecycleRepository hosting; - private final StripeHostingSubscriptionObserver observer; - private final AccountDemoTenantEntitlementRepository demos; - private final AccountTenantAuthorityEventRepository sources; - private final CanonicalGameplayAdmissionDecisionReadClient targets; - private final String namespace; - private final TransactionTemplate transaction; - private final Clock clock; - private final String expectedWorkload; - - public AccountPlayerAdmissionEntitlementOwner( - DSLContext dsl, - AccountRepository accounts, - AccountGameplayAdmissionCallerVerifier callers, - AccountGameplayDelegationIssuanceRepository issuances, - AccountCanonicalRuntimeMembershipSnapshotRepository memberships, - AccountConnectScopeRepository scopes, - AccountHostingSubscriptionLifecycleRepository hosting, - StripeHostingSubscriptionObserver observer, - AccountDemoTenantEntitlementRepository demos, - AccountTenantAuthorityEventRepository sources, - CanonicalGameplayAdmissionDecisionReadClient targets, - PlatformTransactionManager transactions, - Clock clock, - String workloadNamespace) { - this.dsl = Objects.requireNonNull(dsl); - this.accounts = Objects.requireNonNull(accounts); - this.callers = Objects.requireNonNull(callers); - this.issuances = Objects.requireNonNull(issuances); - this.memberships = Objects.requireNonNull(memberships); - this.scopes = Objects.requireNonNull(scopes); - this.hosting = Objects.requireNonNull(hosting); - this.observer = Objects.requireNonNull(observer); - this.demos = Objects.requireNonNull(demos); - this.sources = Objects.requireNonNull(sources); - this.targets = Objects.requireNonNull(targets); - this.namespace = workloadNamespace; - this.clock = Objects.requireNonNull(clock); - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { - throw new IllegalArgumentException("Canonical Game Session workload namespace is required"); - } - expectedWorkload = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; - transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); - transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - transaction.setReadOnly(false); - } - - /** Selects the sole current Account-owned billing source; callers cannot select a family. */ - public RuntimePlayerAdmissionEntitlementEvidence evaluate( - Request request, String presentedInitialLoginJwt) { - VerifiedCaller caller = verifyCaller(request, presentedInitialLoginJwt); - Prepared prepared = - inSourceTransaction( - () -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - return new Prepared(player, sources.readCurrentSourceSelection(request.tenantId())); - }); - requireCurrentTimes(prepared.player(), now()); - RuntimePlayerAdmissionEntitlementEvidence evidence = - switch (prepared.selection().kind()) { - case PAID_HOSTING -> capturePaidSources(request, caller, prepared); - case NON_PAID_DEMO -> captureDemoSources(request, caller, prepared); - }; - evidence.requireCurrentAt(now()); - return evidence; - } - - private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( - Request request, VerifiedCaller caller, Prepared prepared) { - var fence = inSourceTransaction(() -> hosting.prepareCurrentRead(request.tenantId())); - requireNoAmbientTransaction(); - var observation = observer.observe(fence.binding()); - PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); - return inSourceTransaction( - () -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - if (!prepared.player().scope().equals(player.scope())) throw unavailable(); - requireSameHead(request, prepared.selection()); - var receipt = hosting.readCurrent(fence, observation); - Instant evaluatedAt = now(); - requireFreshReceipt(request, receipt, evaluatedAt); - var event = receipt.tenantAuthorityEvent(); - if (!prepared.selection().matches(event)) throw unavailable(); - requireTenantSource( - player.snapshot(), - event.tenantId(), - event.tenantAuthorityGeneration(), - receipt.tenantBillingSequence(), - event.outboxStreamKey(), - event.outboxSequence(), - event.eventId(), - event.eventDigest()); - if (!receipt.billingEventId().equals(event.tenantBillingEventId()) - || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest()) - || receipt.tenantBillingSequence() != event.tenantBillingSequence()) { - throw unavailable(); - } - requireCurrentTimes(player, evaluatedAt); - var quote = receipt.current().planQuote(); - return capture( - request, - player, - target, - facts( - "PAID_HOSTING", - receipt.subscriptionStatus().storageValue(), - receipt.gameplayAvailable(), - receipt.allowPublicJoin(), - receipt.allowNewGameplayBindings(), - receipt.allowNewInstanceStarts(), - quote.maxActiveSessions(), - quote.maxConcurrentGameInstances(), - quote.maxStorageBytes(), - receipt.entitlementVersion(), - receipt.tenantBillingSequence(), - event.tenantAuthorityGeneration()), - RuntimePlayerAdmissionEntitlementEvidence.digest( - Map.of( - "receiptRequestId", receipt.receiptRequestId().toString(), - "subscriptionId", receipt.current().subscriptionId().toString(), - "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), - "billingEventId", receipt.billingEventId().toString(), - "billingEventDigest", receipt.billingEventDigest(), - "tenantAuthorityEventDigest", event.eventDigest())), - evaluatedAt, - receipt.validUntil()); - }); - } - - private RuntimePlayerAdmissionEntitlementEvidence captureDemoSources( - Request request, VerifiedCaller caller, Prepared prepared) { - PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); - return inSourceTransaction( - () -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - if (!prepared.player().scope().equals(player.scope())) throw unavailable(); - requireSameHead(request, prepared.selection()); - DemoTenantEntitlementSnapshot demo = demos.readCurrent(request.tenantId()); - var head = prepared.selection().checkpoint(); - if (!demo.tenantAuthorityEventId().equals(head.eventId()) - || !demo.tenantAuthorityEventDigest().equals(head.eventDigest()) - || !demo.canonicalTenantId().equals(head.tenantId()) - || demo.tenantAuthorityGeneration() != head.tenantAuthorityGeneration() - || !demo.tenantAuthorityOutboxStreamKey().equals(head.outboxStreamKey()) - || demo.tenantAuthorityOutboxSequence() != head.outboxSequence() - || demo.tenantBillingSequence() != head.tenantBillingSequence() - || !demo.eventId().equals(head.tenantBillingEventId()) - || !demo.eventDigest().equals(head.tenantBillingEventDigest()) - || demo.tenantAuthoritySourceVersion() != head.tenantAuthoritySourceVersion()) { - throw unavailable(); - } - requireTenantSource( - player.snapshot(), - demo.canonicalTenantId(), - demo.tenantAuthorityGeneration(), - demo.tenantBillingSequence(), - demo.tenantAuthorityOutboxStreamKey(), - demo.tenantAuthorityOutboxSequence(), - demo.tenantAuthorityEventId(), - demo.tenantAuthorityEventDigest()); - Instant capturedAt = now(); - requireCurrentTimes(player, capturedAt); - return capture( - request, - player, - target, - facts( - "NON_PAID_DEMO", - null, - demo.gameplayAvailable(), - demo.allowPublicJoin(), - demo.allowNewGameplayBindings(), - demo.allowNewInstanceStarts(), - demo.quotas().maxActiveSessions(), - demo.quotas().maxConcurrentGameInstances(), - demo.quotas().maxStorageBytes(), - demo.entitlementVersion(), - demo.tenantBillingSequence(), - demo.tenantAuthorityGeneration()), - demo.snapshotIdentity(), - capturedAt, - null); - }); - } - - private VerifiedCaller verifyCaller(Request request, String token) { - Objects.requireNonNull(request, "Player entitlement request is required"); - requireNoAmbientTransaction(); - if (!expectedWorkload.equals(request.authenticatedCallerWorkload()) - || !namespace.equals(request.target().targetNamespace()) - || SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService() - || SessionContext.getServiceName() != null - || SessionContext.getServiceInstanceId() != null) throw unavailable(); - VerifiedCaller caller = callers.verifyPresentedCompactToken(token); - if (!expectedWorkload.equals(caller.identity().callerWorkload()) - || !request.target().accountId().equals(caller.identity().accountId())) throw unavailable(); - return caller; - } - - private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) { - UUID accountId = caller.identity().accountId(); - var account = - accounts - .findByAccountUuidForUpdate(accountId) - .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); - if (!accountId.equals(account.getAccountUuid())) throw unavailable(); - CommittedCandidateVerificationData current = - issuances - .readCurrentCommittedCandidateByJti(caller.identity().tokenJti()) - .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); - if (!CommittedCandidateVerificationData.hasSameOwnerEvidence( - caller.currentCandidate(), current)) { - throw unavailable(); - } - Snapshot snapshot = memberships.readCurrent(accountId, request.tenantId()); - RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot); - var authority = current.authoritySnapshot(); - var tuple = snapshot.authorityTuple(); - var expectedCutoff = - authority - .accountSecurityCutoff() - .map( - cutoff -> - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence())); - var actualCutoff = - tuple - .accountSecurityCutoff() - .map( - cutoff -> - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence())); - if (!ISSUER.equals(snapshot.issuerId()) - || !accountId.toString().equals(snapshot.accountId()) - || !request.tenantId().toString().equals(snapshot.tenantId()) - || !accountId.equals(authority.accountId()) - || !Long.toString(authority.issuerGeneration()).equals(tuple.issuerAuthGeneration()) - || !Long.toString(authority.accountGeneration()).equals(tuple.accountAuthorityGeneration()) - || !Long.toString(authority.issuanceFence()).equals(snapshot.issuanceFence()) - || !expectedCutoff.equals(actualCutoff) - || !tuple.privateRealmGrantVersions().isEmpty()) { - throw unavailable(); - } - var verifiedScope = - scopes - .findCanonical(request.connectScopeId()) - .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); - CanonicalConnectScopeEvidence scope = - scopes - .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(request.connectScopeId())) - .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); - if (!"PUBLIC_PRODUCTION".equals(scope.targetClass()) - || scope.tenantProvenance().kind() != TenantProvenanceKind.FRESH_GAME_DESIGN - || scope.tenantProvenance().legacyTenantId() != null - || !accountId.equals(scope.accountUuid()) - || !request.tenantId().equals(scope.tenantUuid()) - || !AccountJoinDigest.scopeV2(verifiedScope).equals(scope.scopeDigest()) - || !Objects.equals(account.getId(), scope.privateAccountId())) { - throw unavailable(); - } - if (!request.target().equals(selector(request, scope))) throw unavailable(); - return new CurrentPlayer(snapshot, scope, current); - } - - private static void requireTenantSource( - Snapshot snapshot, - UUID tenantId, - long generation, - long billingSequence, - String stream, - long sequence, - UUID eventId, - String eventDigest) { - String tenant = snapshot.tenantId(); - TenantBillingCutoff cutoff = - new TenantBillingCutoff( - Long.toString(generation), - Long.toString(billingSequence), - stream, - Long.toString(sequence)); - if (!tenant.equals(tenantId.toString()) - || !TenantAuthorityEventV1Codec.streamKey(tenantId).equals(stream) - || !snapshot - .authorityTuple() - .tenantAuthorityGeneration() - .equals(Map.of(tenant, Long.toString(generation))) - || !snapshot - .authorityTuple() - .tenantBillingCutoff() - .filter(Map.of(tenant, cutoff)::equals) - .isPresent() - || snapshot.sourceEvidence().stream() - .noneMatch( - source -> - stream.equals(source.outboxStreamKey()) - && Long.toString(sequence).equals(source.outboxSequence()) - && eventId.toString().equals(source.eventId()) - && eventDigest.equals(source.eventDigest()))) { - throw unavailable(); - } - } - - private static void requireFreshReceipt( - Request request, AccountHostingSubscriptionCurrentReceipt receipt, Instant now) { - if (!request.tenantId().equals(receipt.current().tenantId()) - || receipt.evaluatedAt() == null - || receipt.validUntil() == null - || now.isBefore(receipt.evaluatedAt()) - || !now.isBefore(receipt.validUntil())) { - throw unavailable(); - } - } - - private static void requireCurrentTimes(CurrentPlayer player, Instant evaluatedAt) { - CanonicalConnectScopeEvidence scope = player.scope(); - var identity = player.issuance().identity(); - if (evaluatedAt.isBefore(Instant.parse(scope.evaluatedAt())) - || !evaluatedAt.isBefore(Instant.parse(scope.connectScopeExpiresAt())) - || evaluatedAt.getEpochSecond() < identity.notBeforeEpochSecond() - || evaluatedAt.getEpochSecond() >= identity.expiresAtEpochSecond()) { - throw unavailable(); - } - } - - private T inSourceTransaction(Supplier action) { - requireNoAmbientTransaction(); - return Objects.requireNonNull( - transaction.execute( - status -> { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - throw unavailable(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != Connection.TRANSACTION_SERIALIZABLE) { - throw unavailable(); - } - }); - return Objects.requireNonNull(action.get()); - })); - } - - private Instant now() { - return clock.instant().truncatedTo(ChronoUnit.MICROS); - } - - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); - } - - private static IllegalStateException unavailable() { - return new IllegalStateException( - "ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable"); - } - - private void requireSameHead(Request request, SourceSelection selected) { - SourceSelection current = sources.readCurrentSourceSelection(request.tenantId()); - if (selected.kind() != current.kind() || !selected.matches(current.checkpoint())) - throw unavailable(); - } - - /** Trusted method-authorized workload assertion; construction does not authenticate a peer. */ - public record Request( - RetainedTargetSelector target, String connectScopeId, String authenticatedCallerWorkload) { - public Request { - Objects.requireNonNull(target, "Exact resolved target selectors are required"); - if (connectScopeId == null || connectScopeId.isBlank() || connectScopeId.length() > 16384) - throw new IllegalArgumentException("Bounded opaque connect scope is required"); - GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) - .filter( - peer -> - peer.uri().equals(authenticatedCallerWorkload) - && "game-session-service".equals(peer.service())) - .orElseThrow( - () -> new IllegalArgumentException("Exact Game Session workload is required")); - } - - public UUID tenantId() { - return target.tenantId(); - } - - public UUID requestId() { - return target.readRequestId(); - } - - @Override - public String toString() { - return "PlayerAdmissionEntitlementRequest[redacted]"; - } - } - - private static RetainedTargetSelector selector( - Request request, CanonicalConnectScopeEvidence scope) { - return new RetainedTargetSelector( - request.requestId(), - scope.accountUuid(), - request.target().targetNamespace(), - scope.tenantUuid(), - scope.tenantSlug(), - scope.worldSlug(), - scope.realmId(), - scope.realmSlug(), - scope.playableStateNamespaceUuid(), - scope.playableStateScope(), - scope.gameInstanceUuid(), - scope.catalogRevision(), - scope.pointerVersion()); - } - - private PublishedRealmEvidence readProtectedTarget( - Request request, CanonicalConnectScopeEvidence scope) { - requireNoAmbientTransaction(); - var selector = selector(request, scope); - var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); - if (!selector.equals(resolved.selector())) throw unavailable(); - CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( - selector, resolved.currentTarget()); - var result = - Objects.requireNonNull(targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); - if (!resolved.strictSelector().equals(result.selector()) - || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); - return result; - } - - private static RuntimePlayerAdmissionEntitlementEvidence capture( - Request request, - CurrentPlayer player, - PublishedRealmEvidence target, - Map facts, - String entitlementSourceDigest, - Instant time, - Instant paidReceiptValidUntil) { - var scope = player.scope(); - var current = target.currentTarget(); - Map binding = new LinkedHashMap<>(); - binding.put("targetClass", "PUBLIC_PRODUCTION"); - binding.put("characterCreationPolicy", "PRESEEDED_ONLY"); - binding.put("targetNamespace", current.targetNamespace()); - binding.put("tenantId", scope.tenantUuid().toString()); - binding.put("tenantSlug", scope.tenantSlug()); - binding.put("worldSlug", scope.worldSlug()); - binding.put("realmId", scope.realmId().toString()); - binding.put("realmSlug", scope.realmSlug()); - binding.put("playableStateNamespaceId", scope.playableStateNamespaceUuid().toString()); - binding.put("playableStateScope", scope.playableStateScope()); - binding.put("gameInstanceId", scope.gameInstanceUuid().toString()); - binding.put("canonicalVersionId", current.canonicalVersionId().toString()); - binding.put("catalogRevision", Long.toString(scope.catalogRevision())); - binding.put("pointerVersion", Long.toString(scope.pointerVersion())); - binding.put("activeWorldEpoch", Long.toString(current.activeWorldEpoch())); - binding.put("evaluatedAt", scope.evaluatedAt()); - binding.put("connectScopeExpiresAt", scope.connectScopeExpiresAt()); - var caller = player.issuance(); - var world = target.worldLifecycleEvidence(); - Map sources = new LinkedHashMap<>(); - sources.put("callerTokenJti", caller.identity().tokenJti().toString()); - sources.put( - "callerTokenExpiresAt", - Instant.ofEpochSecond(caller.identity().expiresAtEpochSecond()).toString()); - sources.put( - "paidReceiptValidUntil", - paidReceiptValidUntil == null ? null : paidReceiptValidUntil.toString()); - sources.put("callerTokenSha256", caller.tokenSha256()); - sources.put("callerRegistryRecordSha256", caller.canonicalRegistryRecordSha256()); - sources.put("callerCommitProofSha256", caller.commitProofSha256()); - sources.put("callerContextId", caller.identity().callerContextId().toString()); - sources.put("callerOperationId", caller.identity().operationId().toString()); - sources.put("scopeDigest", scope.scopeDigest()); - sources.put("entitlementSourceDigest", entitlementSourceDigest); - sources.put( - "admissionPointerSnapshotDigest", target.sourceEvidence().admissionPointerSnapshotDigest()); - sources.put( - "gameSessionOwnerProofDigest", - target.sourceEvidence().gameSessionOwnerProof().proofDigest()); - sources.put( - "publishedPolicySetDigest", - target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); - sources.put( - "worldLifecycleDigest", - RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); - sources.put("worldCaptureId", world.captureId().toString()); - sources.put("worldRowVersion", Long.toString(world.rowVersion())); - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - request.requestId(), - request.authenticatedCallerWorkload(), - request.connectScopeId(), - player.snapshot(), - binding, - facts, - sources, - time); - } - - private static Map facts( - String kind, - String status, - boolean gameplay, - boolean join, - boolean bindings, - boolean starts, - long sessions, - long instances, - long storage, - long version, - long sequence, - long generation) { - Map result = new LinkedHashMap<>(); - result.put("sourceKind", kind); - result.put("subscriptionStatus", status); - result.put("provisioningStatus", null); - result.put("gameplayAvailable", gameplay); - result.put("allowPublicJoin", join); - result.put("allowNewGameplayBindings", bindings); - result.put("allowNewInstanceStarts", starts); - result.put( - "quotas", - Map.of( - "maxActiveSessions", - Long.toString(sessions), - "maxConcurrentGameInstances", - Long.toString(instances), - "maxStorageBytes", - Long.toString(storage))); - result.put("entitlementVersion", Long.toString(version)); - result.put("tenantBillingSequence", Long.toString(sequence)); - result.put("tenantAuthorityGeneration", Long.toString(generation)); - return result; - } - - private record Prepared(CurrentPlayer player, SourceSelection selection) {} - - private record CurrentPlayer( - Snapshot snapshot, - CanonicalConnectScopeEvidence scope, - CommittedCandidateVerificationData issuance) {} -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java deleted file mode 100644 index 2ddf42719a..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.firedevops.firemud.accountservice.service.impl; - -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import io.grpc.TlsServerCredentials; -import io.grpc.stub.StreamObserver; -import java.util.List; -import java.util.Objects; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.TrustManagerFactory; -import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; -import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; -import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; -import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; -import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Unregistered Account owner receiver. No component annotation, capacity commit, World hold or - * gameplay admission. - */ -public final class AccountPlayerAdmissionEntitlementGrpcService - extends AccountPlayerAdmissionEntitlementReadServiceGrpc - .AccountPlayerAdmissionEntitlementReadServiceImplBase { - private final AccountPlayerAdmissionEntitlementOwner owner; - private final String namespace; - private final AccountPlayerAdmissionEntitlementWorkloadGuard guard; - - public AccountPlayerAdmissionEntitlementGrpcService( - AccountPlayerAdmissionEntitlementOwner owner, String namespace) { - this.owner = Objects.requireNonNull(owner); - this.guard = new AccountPlayerAdmissionEntitlementWorkloadGuard(namespace); - this.namespace = namespace; - } - - /** - * Explicit private composition, requiring real client certificates. Returns an unstarted server. - */ - public Server createUnregisteredServer( - String address, KeyManagerFactory keys, TrustManagerFactory trust) { - var factory = - new BoundedGrpcServerFactory( - Objects.requireNonNull(address), - List.of(), - Objects.requireNonNull(keys), - Objects.requireNonNull(trust), - TlsServerCredentials.ClientAuth.REQUIRE, - GrpcRequestBytePolicy.ordinary(), - RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); - factory.addService(ServerInterceptors.interceptForward(this, guard)); - return factory.createServer(); - } - - @Override - public void readPlayerAdmissionEntitlement( - ReadPlayerAdmissionEntitlementRequest wire, - StreamObserver observer) { - Objects.requireNonNull(observer); - final String authenticatedCaller; - try { - authenticatedCaller = guard.requireAuthenticatedGameSessionCaller(); - } catch (StatusRuntimeException denied) { - fail(observer, denied.getStatus()); - return; - } - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } - final RuntimePlayerAdmissionEntitlementGrpcCodec.PresentedRequest presented; - if (wire == null) { - fail(observer, Status.INVALID_ARGUMENT); - return; - } - try { - presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); - } catch (IllegalArgumentException invalid) { - fail(observer, Status.INVALID_ARGUMENT); - return; - } - var request = presented.request(); - if (!namespace.equals(request.target().targetNamespace())) { - fail(observer, Status.PERMISSION_DENIED); - return; - } - final ReadPlayerAdmissionEntitlementResponse response; - try { - var sourceRequest = - new AccountPlayerAdmissionEntitlementOwner.Request( - request.target(), request.connectScopeId(), authenticatedCaller); - var evidence = owner.evaluate(sourceRequest, presented.initialLoginJwt()); - response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, evidence); - } catch (RuntimeException unavailableSource) { - // No positive evidence, alternate source, or exception details escape an unavailable - // evaluation. - fail(observer, Status.UNAVAILABLE); - return; - } - try { - observer.onNext(response); - } catch (RuntimeException callbackFailure) { - fail(observer, Status.INTERNAL); - return; - } - observer.onCompleted(); - } - - private static void fail(StreamObserver observer, Status status) { - observer.onError( - Status.fromCode(status.getCode()) - .withDescription("Player-admission entitlement evidence is unavailable") - .asRuntimeException()); - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index a36e2e21ba..cd5a6a33dd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -1434,21 +1434,8 @@ Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exce return newFixture(redisClient, "latest"); } - Fixture newPlayerEntitlementFixture(AccountGameplayDelegationRedisClient redisClient) - throws Exception { - return newFixture(redisClient, "latest", true); - } - private Fixture newFixture( AccountGameplayDelegationRedisClient redisClient, String migrationTarget) throws Exception { - return newFixture(redisClient, migrationTarget, false); - } - - private Fixture newFixture( - AccountGameplayDelegationRedisClient redisClient, - String migrationTarget, - boolean currentScope) - throws Exception { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); if (schema.length() > 63) throw new IllegalStateException("Generated schema name is too long"); runOwnedSchemas.add(schema); @@ -1465,8 +1452,7 @@ private Fixture newFixture( DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); - return new Fixture( - schema, dataSource, dsl, manager, temporaryDirectory, redisClient, currentScope); + return new Fixture(schema, dataSource, dsl, manager, temporaryDirectory, redisClient); } private static int awaitBackendBlockedBy( @@ -2055,8 +2041,7 @@ private Fixture( DSLContext dsl, DataSourceTransactionManager manager, Path temporaryDirectory, - AccountGameplayDelegationRedisClient redisClient, - boolean currentScope) + AccountGameplayDelegationRedisClient redisClient) throws Exception { this.schema = schema; this.dataSource = dataSource; @@ -2126,31 +2111,7 @@ private Fixture( newAccount.setPasswordHash("integration-fixture-password-hash"); newAccount.setRole("player"); this.account = transaction.execute(status -> accounts.save(newAccount)); - var retainedScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); - this.joinScope = - currentScope - ? new CanonicalJoinScopeV2( - retainedScope.connectScopeId(), - retainedScope.accountId(), - retainedScope.tenantId(), - retainedScope.realmId(), - retainedScope.tenantSlug(), - retainedScope.worldSlug(), - retainedScope.realmSlug(), - retainedScope.playableStateNamespaceId(), - retainedScope.playableStateScope(), - retainedScope.gameInstanceId(), - retainedScope.catalogRevision(), - retainedScope.pointerVersion(), - Instant.now() - .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) - .minusSeconds(5) - .toString(), - Instant.now() - .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) - .plusSeconds(120) - .toString()) - : retainedScope; + this.joinScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); establishTenantEntitlementAndMembership(connectScopes); AccountAuthEvidenceBundleRepository bundles = @@ -2164,61 +2125,6 @@ private Fixture( this.committedCandidate = createCommittedIssuanceCandidate(bundles, redisClient); } - CanonicalJoinScopeV2 playerEntitlementScope() { - return joinScope; - } - - void beginPlayerEntitlementLoginRevocation() { - var identity = tokenIdentity(committedCandidate); - UUID requestId = UUID.randomUUID(); - transaction.execute( - status -> - tokenFences.beginRevocationIntent( - identity, - requestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - identity, requestId))); - } - - net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner - playerEntitlementOwner(CanonicalGameplayAdmissionDecisionReadClient protectedTargets) { - var scopes = - new AccountConnectScopeRepository( - dsl, - new AccountTenantIdentityResolver( - mock(ApprovedLegacyTenantAssociationRepository.class), TEST_NAMESPACE), - freshTenants); - var snapshots = - new AccountCanonicalRuntimeMembershipSnapshotRepository( - accounts, - generations, - sourceEvidence, - tenantAuthorityEvents, - freshTenants, - memberships, - membershipPairs, - membershipRoles, - authorityOutbox); - return new net.firedevops.firemud.accountservice.service - .AccountPlayerAdmissionEntitlementOwner( - dsl, - accounts, - new AccountGameplayAdmissionCallerVerifier( - signerFixture.trustedJwksSource(), committedIssuanceOwner, Clock.systemUTC()), - issuance, - snapshots, - scopes, - mock(AccountHostingSubscriptionLifecycleRepository.class), - mock( - net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.class), - demoEntitlements, - tenantAuthorityEvents, - protectedTargets, - manager, - Clock.systemUTC(), - TEST_NAMESPACE); - } - private void establishTenantEntitlementAndMembership( AccountConnectScopeRepository connectScopes) { transaction.execute( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java deleted file mode 100644 index b7fec29bc4..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java +++ /dev/null @@ -1,344 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import io.grpc.Server; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.AuthenticateRequest; -import net.firedevops.firemud.account.v1.AuthenticateResponse; -import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; -import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; -import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; -import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; -import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; -import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Actual committed LOGIN recovery/currentness, PostgreSQL DEMO and membership owners, Account - * receiver and Game Session consumer. Test signer/JWKS custody, initial response delivery and - * protected published Game Session/World inputs remain controlled. This does not prove public - * ingress, the default PLAY route, production custody, admission or activation. - */ -class AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest { - private static final String NAMESPACE = "test"; - private static final String PEER = "spiffe://firemud/ns/test/sa/game-session-service"; - private static final Clock CLOCK = Clock.systemUTC(); - private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtures = - new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); - @TempDir Path directory; - - @BeforeAll - static void startPostgres() { - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); - } - - @AfterAll - static void stopPostgres() { - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); - } - - @AfterEach - void dropSchemas() { - fixtures.dropRunOwnedSchemas(); - } - - @Test - void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Exception { - fixtures.temporaryDirectory = directory; - var pki = - LoopbackMtlsTestPki.create( - directory, - "Actual LOGIN player entitlement composition", - new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), - new LoopbackMtlsTestPki.IdentitySpec( - "account", "spiffe://firemud/ns/test/sa/account-service", true)); - try (var redis = - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture - .start()) { - var f = fixtures.newPlayerEntitlementFixture(redis.client()); - var identity = f.committedCandidate.identity(); - var initial = - InitialGameplayLoginResult.fromRecoveredCredential( - f.responseRecoveryOwner.recoverInitialLoginResponse( - identity.requestId(), - identity.accountId(), - new CallerIdentity(identity.callerWorkload(), identity.callerContextId()))); - var trusted = f.signerFixture.trustedJwksSource(); - var jwks = - new AccountPublicJwksCache( - trusted, trusted.sourceIdentity(), CLOCK, Duration.ofSeconds(30)); - var request = - AuthenticateRequest.newBuilder() - .setRequestId(initial.requestId().toString()) - .setEmail("controlled-delivery@example.test") - .setPassword("controlled-input") - .setSourceContext( - GameplayLoginSourceContext.newBuilder() - .setCallerContextId(initial.callerContextId().toString()) - .setCanonicalClientAddress("203.0.113.10") - .setTransportClass( - GameplayLoginTransportClass - .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) - .build(); - try (var login = - CanonicalGameplayLoginResult.fromAuthenticatedResponse( - projectRecoveredInitial(initial), - request, - new AccountAsymmetricJwtVerifier(jwks, CLOCK), - CLOCK)) { - var scope = f.playerEntitlementScope(); - var protectedTargets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); - controlledTarget(protectedTargets); - var owner = f.playerEntitlementOwner(protectedTargets); - var selector = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - UUID.randomUUID(), - scope.accountId(), - NAMESPACE, - scope.tenantId(), - scope.tenantSlug(), - scope.worldSlug(), - scope.realmId(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion()); - var ownerRequest = - new net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner - .Request(selector, scope.connectScopeId(), PEER); - byte[] compact = login.compactJwtBytes(); - net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence - expected; - try { - expected = owner.evaluate(ownerRequest, new String(compact, StandardCharsets.US_ASCII)); - } finally { - Arrays.fill(compact, (byte) 0); - } - var targetFields = (Map) expected.fields().get("target"); - var sources = (Map) expected.fields().get("sourceReferences"); - var target = mock(CanonicalPlayableTarget.class); - when(target.targetNamespace()).thenReturn(NAMESPACE); - when(target.canonicalTenantId()).thenReturn(scope.tenantId()); - when(target.tenantSlug()).thenReturn(scope.tenantSlug()); - when(target.worldSlug()).thenReturn(scope.worldSlug()); - when(target.realmId()).thenReturn(scope.realmId()); - when(target.realmSlug()).thenReturn(scope.realmSlug()); - when(target.playableStateNamespaceId()).thenReturn(scope.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(scope.playableStateScope()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.canonicalGameInstanceId()).thenReturn(scope.gameInstanceId()); - when(target.canonicalVersionId()) - .thenReturn(UUID.fromString((String) targetFields.get("canonicalVersionId"))); - when(target.catalogRevision()).thenReturn(scope.catalogRevision()); - when(target.pointerVersion()).thenReturn(scope.pointerVersion()); - when(target.activeWorldEpoch()) - .thenReturn(Long.parseLong((String) targetFields.get("activeWorldEpoch"))); - when(target.admissionPointerSnapshotDigest()) - .thenReturn((String) sources.get("admissionPointerSnapshotDigest")); - when(target.ownerProofDigest()) - .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); - var claims = mock(ContextClaims.class); - when(claims.expiresAtMillis()) - .thenReturn(Instant.parse(scope.connectScopeExpiresAt()).toEpochMilli()); - var context = mock(FirstPartyConnectContext.class); - when(context.hasCompleteRoutingScope()).thenReturn(true); - when(context.claims()).thenReturn(claims); - when(context.accountId()).thenReturn(scope.accountId().toString()); - when(context.connectScopeId()).thenReturn(scope.connectScopeId()); - when(context.resolvedTarget()).thenReturn(target); - Server server = - new AccountPlayerAdmissionEntitlementGrpcService(owner, NAMESPACE) - .createUnregisteredServer( - "127.0.0.1:0", - pki.keyManagerFactory(pki.identity("account")), - pki.trustManagerFactory()); - server.start(); - var endpoints = new ServiceEndpointsProperties(); - endpoints.setAccountService("localhost:" + server.getPort()); - try (var client = - new AccountPlayerAdmissionEntitlementClient( - endpoints, - pki.clientProperties(directory, pki.identity("client")), - new GrpcChannelFactory(), - NAMESPACE, - CLOCK)) { - client.init(); - var result = client.read(context, selector.readRequestId(), login, () -> true); - assertThat(result.fields()) - .containsEntry("variant", "PLAYER_ADMISSION") - .containsEntry("sourceKind", "NON_PAID_DEMO"); - assertThat(result.membershipSource().membershipExists()).isTrue(); - assertThat(result.membershipSource().gameplayAdmissionAllowed()).isTrue(); - var receivedSources = (Map) result.fields().get("sourceReferences"); - assertThat(receivedSources.get("callerTokenSha256")).isEqualTo(initial.tokenSha256()); - assertThat(receivedSources.get("callerTokenJti")) - .isEqualTo(initial.tokenJti().toString()); - assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) - .isInstanceOf(RuntimeException.class); - // Retaining valid signature bytes and local custody is insufficient after Account moves. - f.beginPlayerEntitlementLoginRevocation(); - assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) - .isInstanceOf(RuntimeException.class); - login.close(); - assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) - .isInstanceOf(RuntimeException.class); - } finally { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - } - } - - /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ - private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { - when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - when(target.targetNamespace()).thenReturn(selector.targetNamespace()); - when(target.canonicalTenantId()).thenReturn(selector.tenantId()); - when(target.tenantSlug()).thenReturn(selector.tenantSlug()); - when(target.worldSlug()).thenReturn(selector.worldSlug()); - when(target.realmId()).thenReturn(selector.realmId()); - when(target.realmSlug()).thenReturn(selector.realmSlug()); - when(target.playableStateNamespaceId()) - .thenReturn(selector.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(selector.playableStateScope()); - when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); - when(target.catalogRevision()).thenReturn(selector.catalogRevision()); - when(target.pointerVersion()).thenReturn(selector.pointerVersion()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.ownerProofOutcome()) - .thenReturn( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); - UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); - when(target.canonicalVersionId()).thenReturn(version); - when(target.activeWorldEpoch()).thenReturn(5L); - var strict = - new CanonicalGameplayRosterOwnerReadEvidence.Request( - selector.readRequestId(), - selector.accountId(), - selector.targetNamespace(), - selector.tenantId(), - selector.worldSlug(), - selector.realmId(), - selector.realmSlug(), - selector.playableStateNamespaceId(), - selector.playableStateScope(), - selector.gameInstanceId(), - version, - selector.catalogRevision(), - selector.pointerVersion(), - 5L); - var resolved = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget - .class); - when(resolved.selector()).thenReturn(selector); - when(resolved.currentTarget()).thenReturn(target); - when(resolved.strictSelector()).thenReturn(strict); - var read = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - when(read.selector()).thenReturn(strict); - when(read.currentTarget()).thenReturn(target); - var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); - when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); - var policies = mock(PublishedRealmEntryPolicySetEvidence.class); - when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); - when(source.publishedPolicySetEvidence()).thenReturn(policies); - var ownerProof = - mock( - net.firedevops.firemud.common.world - .GameSessionCanonicalInitialAdmissionOwnerProof.class); - when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); - when(source.gameSessionOwnerProof()).thenReturn(ownerProof); - when(read.sourceEvidence()).thenReturn(source); - var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(world.canonicalBytes()) - .thenReturn( - "controlled-complete-world-source" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(world.captureId()) - .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); - when(world.rowVersion()).thenReturn(2L); - when(read.worldLifecycleEvidence()).thenReturn(world); - when(targets.readPublishedRealmAdmissionOwner(strict)) - .thenAnswer( - readCall -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return read; - }); - return resolved; - }); - } - - private static AuthenticateResponse projectRecoveredInitial(InitialGameplayLoginResult result) { - byte[] token = result.compactJwtBytes(); - try { - return AuthenticateResponse.newBuilder() - .setAuthToken(new String(token, StandardCharsets.US_ASCII)) - .setAccountId(result.accountId().toString()) - .setRequestId(result.requestId().toString()) - .setCallerContextId(result.callerContextId().toString()) - .setTokenJti(result.tokenJti().toString()) - .setTokenSha256(result.tokenSha256()) - .setTokenProfile(result.profile()) - .setIssuedAtEpochSeconds(result.issuedAtEpochSecond()) - .setNotBeforeEpochSeconds(result.notBeforeEpochSecond()) - .setExpiresAtEpochSeconds(result.expiresAtEpochSecond()) - .setTokenGeneration(result.tokenGeneration()) - .setIssuanceFence(result.issuanceFence()) - .setAuthorityTupleCanonicalJson(ByteString.copyFrom(result.authorityTupleCanonicalJson())) - .setOutboxCheckpointsCanonicalJson( - ByteString.copyFrom(result.outboxCheckpointsCanonicalJson())) - .setOutboxSourceEventEvidenceCanonicalJson( - ByteString.copyFrom(result.outboxSourceEventEvidenceCanonicalJson())) - .build(); - } finally { - Arrays.fill(token, (byte) 0); - } - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java deleted file mode 100644 index c94ecd8279..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ /dev/null @@ -1,718 +0,0 @@ -package net.firedevops.firemud.accountservice.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.sql.Connection; -import java.sql.SQLException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.HexFormat; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; -import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; -import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; -import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; -import org.flywaydb.core.Flyway; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Physical canonical Account/membership/scope/demo composition and lock/commit proof definitions. - * JWT/JWKS/Redis caller verification and current committed issuance are controlled doubles here; - * the protected GS/World client is also controlled. This does not prove custody, actual issuance, - * paid composition or physical published routing. The explicit loopback composition additionally - * uses the actual Account receiver and Game Session client over mTLS; its LOGIN and target inputs - * remain controlled doubles, not genuine custody or production activation. - */ -class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { - private static final String SCHEMA_PREFIX = "player_entitlement_"; - // Syntax-only credential for the explicitly mocked caller verifier, not a signed LOGIN. - private static final String CONTROLLED_COMPACT_TOKEN = "e30.e30.c2lnbmF0dXJl"; - private static final String NAMESPACE = "player-entitlement-proof"; - private static final String ISSUER = "firemud-account-service"; - private static final String PEER = - "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; - private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); - private static final AccountPostgresIntegrationFixture POSTGRES = - new AccountPostgresIntegrationFixture(); - @TempDir Path certificateDirectory; - private final Set schemas = ConcurrentHashMap.newKeySet(); - - @BeforeAll - static void startPostgres() { - POSTGRES.start(); - } - - @AfterAll - static void stopPostgres() { - POSTGRES.stop(); - } - - @AfterEach - void dropOwnedSchemas() { - JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); - for (String schema : schemas) { - if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { - throw new IllegalStateException("Refusing cleanup of an unowned schema"); - } - jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } - schemas.clear(); - } - - @Test - void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission() - throws Exception { - var pki = - LoopbackMtlsTestPki.create( - certificateDirectory, - "Controlled player admission composition", - new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), - new LoopbackMtlsTestPki.IdentitySpec( - "account", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true)); - for (boolean joined : new boolean[] {false, true}) { - Fixture f = fixture(joined); - var request = f.request(); - var expected = f.owner.evaluate(request, CONTROLLED_COMPACT_TOKEN); - var targetFields = (Map) expected.fields().get("target"); - var sources = (Map) expected.fields().get("sourceReferences"); - // Only the upstream target/custody are doubles. No owner, receiver or consumer is mocked. - var target = mock(CanonicalPlayableTarget.class); - when(target.targetNamespace()).thenReturn(NAMESPACE); - when(target.canonicalTenantId()).thenReturn(f.tenantId); - when(target.tenantSlug()).thenReturn(f.scope.tenantSlug()); - when(target.worldSlug()).thenReturn(f.scope.worldSlug()); - when(target.realmId()).thenReturn(f.scope.realmId()); - when(target.realmSlug()).thenReturn(f.scope.realmSlug()); - when(target.playableStateNamespaceId()).thenReturn(f.scope.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn("SHARED"); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.canonicalGameInstanceId()).thenReturn(f.scope.gameInstanceId()); - when(target.canonicalVersionId()) - .thenReturn(UUID.fromString((String) targetFields.get("canonicalVersionId"))); - when(target.catalogRevision()).thenReturn(f.scope.catalogRevision()); - when(target.pointerVersion()).thenReturn(f.scope.pointerVersion()); - when(target.activeWorldEpoch()) - .thenReturn(Long.parseLong((String) targetFields.get("activeWorldEpoch"))); - when(target.admissionPointerSnapshotDigest()) - .thenReturn((String) sources.get("admissionPointerSnapshotDigest")); - when(target.ownerProofDigest()) - .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); - var claims = mock(ContextClaims.class); - when(claims.expiresAtMillis()).thenReturn(NOW.plusSeconds(120).toEpochMilli()); - var context = mock(FirstPartyConnectContext.class); - when(context.hasCompleteRoutingScope()).thenReturn(true); - when(context.claims()).thenReturn(claims); - when(context.accountId()).thenReturn(f.account.getAccountUuid().toString()); - when(context.connectScopeId()).thenReturn(f.scope.connectScopeId()); - when(context.resolvedTarget()).thenReturn(target); - var login = mock(CanonicalGameplayLoginResult.class); - when(login.compactJwtBytes()) - .thenAnswer(invocation -> CONTROLLED_COMPACT_TOKEN.getBytes(StandardCharsets.US_ASCII)); - when(login.evidence()) - .thenReturn( - new CanonicalGameplayLoginResult.NonSecretEvidence( - f.account.getAccountUuid(), - UUID.randomUUID(), - UUID.fromString((String) sources.get("callerContextId")), - UUID.fromString((String) sources.get("callerTokenJti")), - controlledTokenDigest(), - GameSessionAccountDelegationProfile.PROFILE, - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond(), - "1", - "1", - ByteString.EMPTY, - ByteString.EMPTY, - ByteString.EMPTY)); - var receiver = new AccountPlayerAdmissionEntitlementGrpcService(f.owner, NAMESPACE); - var server = - receiver.createUnregisteredServer( - "127.0.0.1:0", - pki.keyManagerFactory(pki.identity("account")), - pki.trustManagerFactory()); - server.start(); - long membershipsBefore = f.dsl.fetchCount(DSL.table("account_tenant_membership")); - var endpoints = new ServiceEndpointsProperties(); - endpoints.setAccountService("localhost:" + server.getPort()); - try (var client = - new AccountPlayerAdmissionEntitlementClient( - endpoints, - pki.clientProperties(certificateDirectory, pki.identity("client")), - new GrpcChannelFactory(), - NAMESPACE, - Clock.fixed(NOW, ZoneOffset.UTC))) { - client.init(); - var received = client.read(context, request.requestId(), login, () -> true); - assertThat(received.canonicalBytes()).isEqualTo(expected.canonicalBytes()); - assertThat(received.membershipSource().membershipExists()).isEqualTo(joined); - assertThat(received.membershipSource().gameplayAdmissionAllowed()).isEqualTo(joined); - assertThat(new String(received.canonicalBytes(), StandardCharsets.UTF_8)) - .doesNotContain(CONTROLLED_COMPACT_TOKEN); - assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) - .isInstanceOf(RuntimeException.class); - assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))) - .isEqualTo(membershipsBefore); - } finally { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - } - - private static String controlledTokenDigest() { - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(CONTROLLED_COMPACT_TOKEN.getBytes(StandardCharsets.US_ASCII))); - } catch (java.security.NoSuchAlgorithmException unavailable) { - throw new IllegalStateException(unavailable); - } - } - - @Test - void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { - Fixture f = fixture(false); - long before = f.dsl.fetchCount(DSL.table("account_tenant_membership")); - var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); - assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); - assertThat(value.membershipSource().accountId()) - .isEqualTo(f.account.getAccountUuid().toString()); - assertThat(value.membershipSource().tenantId()).isEqualTo(f.tenantId.toString()); - assertThat(value.membershipSource().membershipExists()).isFalse(); - assertThat(value.membershipSource().membershipLifecycleState()).isEqualTo("MISSING"); - assertThat(value.membershipSource().gameplayAdmissionAllowed()).isFalse(); - assertThat(value.fields()).containsEntry("sourceKind", "NON_PAID_DEMO"); - assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))).isEqualTo(before); - var missing = - f.transaction.execute( - status -> f.memberships.findFreshMembership(f.account.getAccountUuid(), f.tenantId)); - assertThat(missing).isEmpty(); - assertThat(value.membershipSource().checkpoints()) - .anySatisfy( - checkpoint -> { - assertThat(checkpoint.outboxStreamKey()).contains("membership/"); - assertThat(checkpoint.outboxSequence()).isEqualTo("0"); - }); - assertThat(value.membershipSource().sourceEvidence()).isNotEmpty(); - } - - @Test - void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { - Fixture f = fixture(true); - var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); - assertThat(value.membershipSource().membershipExists()).isTrue(); - assertThat(value.membershipSource().membershipVersion()) - .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); - assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); - assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); - var binding = (Map) value.fields().get("target"); - assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); - assertThat(binding.get("playableStateNamespaceId")) - .isEqualTo(f.scope.playableStateNamespaceId().toString()); - assertThat(binding.get("gameInstanceId")).isEqualTo(f.scope.gameInstanceId().toString()); - assertThat(binding.get("catalogRevision")).isEqualTo("7"); - assertThat(binding.get("pointerVersion")).isEqualTo("3"); - assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), CONTROLLED_COMPACT_TOKEN); - } - - @Test - void captureHoldsActualAccountWriterLockAndFailureBeforeCommitExposesNoValue() { - Fixture f = fixture(false); - AtomicBoolean competingWriterRefused = new AtomicBoolean(); - doAnswer( - invocation -> { - Object snapshot = invocation.callRealMethod(); - try (Connection contender = f.dataSource.getConnection()) { - contender.setAutoCommit(false); - try (var statement = contender.createStatement()) { - statement.execute("SET LOCAL lock_timeout = '150ms'"); - try (var select = - contender.prepareStatement( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE")) { - select.setObject(1, f.account.getAccountUuid()); - try { - select.executeQuery().close(); - throw new AssertionError( - "Account source lock did not exclude a competing writer"); - } catch (SQLException expectedLockTimeout) { - assertThat(expectedLockTimeout.getSQLState()).isEqualTo("55P03"); - competingWriterRefused.set(true); - } - } finally { - contender.rollback(); - } - } - } - TransactionSynchronizationManager.registerSynchronization( - new TransactionSynchronization() { - @Override - public void beforeCommit(boolean readOnly) { - throw new IllegalStateException("controlled final source commit refusal"); - } - }); - return snapshot; - }) - .when(f.demos) - .readCurrent(f.tenantId); - assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) - .hasMessageContaining("controlled final source commit refusal"); - assertThat(competingWriterRefused.get()).isTrue(); - var unlocked = - f.transaction.execute( - status -> f.accounts.findByAccountUuidForUpdate(f.account.getAccountUuid())); - assertThat(unlocked).isPresent(); - } - - private Fixture fixture(boolean join) { - String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); - schemas.add(schema); - DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); - return new Fixture(dataSource, join); - } - - /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ - private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { - when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - when(target.targetNamespace()).thenReturn(selector.targetNamespace()); - when(target.canonicalTenantId()).thenReturn(selector.tenantId()); - when(target.tenantSlug()).thenReturn(selector.tenantSlug()); - when(target.worldSlug()).thenReturn(selector.worldSlug()); - when(target.realmId()).thenReturn(selector.realmId()); - when(target.realmSlug()).thenReturn(selector.realmSlug()); - when(target.playableStateNamespaceId()) - .thenReturn(selector.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(selector.playableStateScope()); - when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); - when(target.catalogRevision()).thenReturn(selector.catalogRevision()); - when(target.pointerVersion()).thenReturn(selector.pointerVersion()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.ownerProofOutcome()) - .thenReturn( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); - UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); - when(target.canonicalVersionId()).thenReturn(version); - when(target.activeWorldEpoch()).thenReturn(5L); - var strict = - new CanonicalGameplayRosterOwnerReadEvidence.Request( - selector.readRequestId(), - selector.accountId(), - selector.targetNamespace(), - selector.tenantId(), - selector.worldSlug(), - selector.realmId(), - selector.realmSlug(), - selector.playableStateNamespaceId(), - selector.playableStateScope(), - selector.gameInstanceId(), - version, - selector.catalogRevision(), - selector.pointerVersion(), - 5L); - var resolved = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget - .class); - when(resolved.selector()).thenReturn(selector); - when(resolved.currentTarget()).thenReturn(target); - when(resolved.strictSelector()).thenReturn(strict); - var read = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - when(read.selector()).thenReturn(strict); - when(read.currentTarget()).thenReturn(target); - var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); - when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); - var policies = mock(PublishedRealmEntryPolicySetEvidence.class); - when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); - when(source.publishedPolicySetEvidence()).thenReturn(policies); - var ownerProof = - mock( - net.firedevops.firemud.common.world - .GameSessionCanonicalInitialAdmissionOwnerProof.class); - when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); - when(source.gameSessionOwnerProof()).thenReturn(ownerProof); - when(read.sourceEvidence()).thenReturn(source); - var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(world.canonicalBytes()) - .thenReturn( - "controlled-complete-world-source" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(world.captureId()) - .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); - when(world.rowVersion()).thenReturn(2L); - when(read.worldLifecycleEvidence()).thenReturn(world); - when(targets.readPublishedRealmAdmissionOwner(strict)) - .thenAnswer( - readCall -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return read; - }); - return resolved; - }); - } - - private static final class Fixture { - private final DriverManagerDataSource dataSource; - private final DSLContext dsl; - private final TransactionTemplate transaction; - private final AccountRepository accounts; - private final AccountTenantMembershipRepository memberships; - private final AccountDemoTenantEntitlementRepository demos; - private final Account account; - private final UUID tenantId = UUID.randomUUID(); - private final CanonicalJoinScopeV2 scope; - private final AccountPlayerAdmissionEntitlementOwner owner; - - private Fixture(DriverManagerDataSource dataSource, boolean join) { - this.dataSource = dataSource; - dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var transactions = new DataSourceTransactionManager(dataSource); - transaction = new TransactionTemplate(transactions); - accounts = new AccountRepository(dsl); - var tenants = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); - var pairs = new AccountMembershipPairAuthorityRepository(dsl); - memberships = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); - var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); - var generations = new AccountAuthorityGenerationRepository(dsl); - var outbox = new AccountAuthorityOutboxRepository(dsl); - var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - var billing = new AccountTenantEntitlementOutboxRepository(dsl); - var tenantEvents = - new AccountTenantAuthorityEventRepository(dsl, outbox, billing, tenants, generations); - demos = - spy( - new AccountDemoTenantEntitlementRepository( - dsl, tenants, generations, billing, tenantEvents)); - var scopes = - new AccountConnectScopeRepository( - dsl, - new AccountTenantIdentityResolver( - mock(ApprovedLegacyTenantAssociationRepository.class), NAMESPACE), - tenants); - var operations = new AccountJoinOperationRepository(dsl, scopes); - var membershipProducer = - new AccountMembershipAuthorityEventProducer( - operations, - accounts, - pairs, - memberships, - roles, - generations, - outbox, - sources, - tenantEvents, - demos); - var terminal = - new AccountCanonicalFirstJoinTerminalCoordinator( - accounts, - operations, - memberships, - roles, - outbox, - pairs, - new AccountAuditOutboxRepository(dsl), - membershipProducer); - var snapshots = - new AccountCanonicalRuntimeMembershipSnapshotRepository( - accounts, - generations, - sources, - tenantEvents, - tenants, - memberships, - pairs, - roles, - outbox); - Account input = new Account(); - String suffix = UUID.randomUUID().toString().replace("-", ""); - input.setUsername("player-" + suffix); - input.setEmail("player-entitlement-" + suffix + "@example.test"); - input.setPasswordHash("controlled-password-hash"); - // Gameplay player roles belong to the canonical tenant membership. - account = transaction.execute(status -> accounts.save(input)); - if (account == null) throw new IllegalStateException("Account insertion is absent"); - FreshTenantCreationEvidence tenantSource = tenantSource(tenantId); - var provenance = - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - tenantSource.operationId(), - tenantSource.evidenceDigest()); - scope = - new CanonicalJoinScopeV2( - "scope-" + UUID.randomUUID(), - account.getAccountUuid(), - tenantId, - UUID.randomUUID(), - "tenant", - "world", - "production", - UUID.randomUUID(), - "SHARED", - UUID.randomUUID(), - 7, - 3, - NOW.minusSeconds(20).toString(), - NOW.plusSeconds(120).toString()); - String joinRequestId = UUID.randomUUID().toString(); - String callerBinding = "controlled-join-caller"; - transaction.execute( - status -> { - tenants.importVerified(tenantSource); - sources.initializeIssuerIfAbsent(ISSUER); - generations.initializeTenantIfAbsent(tenantId); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantId)); - scopes.insertCanonical(account.getId(), scope, provenance); - operations.insertCanonicalIntent(joinRequestId, scope, callerBinding); - return null; - }); - var entitlement = - transaction.execute( - status -> - demos.provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - tenantId, - tenantSource.creationRequestId(), - tenantSource.requestDigest(), - null, - null, - null, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)), - tenantSource)); - if (entitlement == null) throw new IllegalStateException("Demo source is absent"); - transaction.execute( - status -> { - operations.bindCanonicalPolicyEvidence( - joinRequestId, - scope, - callerBinding, - entitlement.allowPublicJoin(), - entitlement.entitlementVersion()); - if (join) { - terminal.commitCanonicalFirstJoin(scope, joinRequestId, callerBinding); - } else { - accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); - memberships.prepareFreshCreatorAbsence(account.getAccountUuid(), tenantId); - } - return null; - }); - var issuances = mock(AccountGameplayDelegationIssuanceRepository.class); - var callers = mock(AccountGameplayAdmissionCallerVerifier.class); - var identity = - new AccountGameplayDelegationPendingIdentity( - UUID.randomUUID(), - UUID.randomUUID(), - account.getAccountUuid(), - PEER, - UUID.randomUUID(), - mock(AccountGameplayCredentialRequestBinding.class), - "a".repeat(64), - UUID.randomUUID(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond()); - var candidate = mock(CommittedCandidateVerificationData.class); - when(candidate.identity()).thenReturn(identity); - when(candidate.authoritySnapshot()) - .thenReturn( - new AccountAuthoritySnapshot( - account.getAccountUuid(), 1, 1, 1, 1, 1, 1, Optional.empty())); - when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); - when(candidate.signerCorrespondence()) - .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); - when(candidate.tokenSha256()).thenReturn(controlledTokenDigest()); - when(candidate.signerKid()).thenReturn("controlled-kid"); - when(candidate.signerGeneration()).thenReturn("1"); - when(candidate.canonicalRegistryRecordSha256()).thenReturn("b".repeat(64)); - when(candidate.commitProofSha256()).thenReturn("c".repeat(64)); - when(candidate.envelopeKeyId()).thenReturn("controlled-key"); - when(candidate.envelopeSha256()).thenReturn("d".repeat(64)); - var caller = mock(VerifiedCaller.class); - when(caller.identity()).thenReturn(identity); - when(caller.currentCandidate()).thenReturn(candidate); - when(callers.verifyPresentedCompactToken(CONTROLLED_COMPACT_TOKEN)).thenReturn(caller); - when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - dsl.connection( - connection -> - assertThat(connection.getTransactionIsolation()) - .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); - return Optional.of(candidate); - }); - var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); - controlledTarget(targets); - owner = - new AccountPlayerAdmissionEntitlementOwner( - dsl, - accounts, - callers, - issuances, - snapshots, - scopes, - mock(AccountHostingSubscriptionLifecycleRepository.class), - mock(StripeHostingSubscriptionObserver.class), - demos, - tenantEvents, - targets, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC), - NAMESPACE); - } - - private Request request() { - return new Request( - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - UUID.randomUUID(), - account.getAccountUuid(), - NAMESPACE, - tenantId, - scope.tenantSlug(), - scope.worldSlug(), - scope.realmId(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion()), - scope.connectScopeId(), - PEER); - } - } - - private static FreshTenantCreationEvidence tenantSource(UUID tenantId) { - UUID requestId = UUID.randomUUID(); - UUID operationId = UUID.randomUUID(); - String sourceKey = "w-" + UUID.randomUUID().toString().replace("-", ""); - String requestDigest = - GameTenantCreationDigest.requestDigest(NAMESPACE, requestId, sourceKey, "World", null); - return new FreshTenantCreationEvidence( - 1, - NAMESPACE, - requestId, - operationId, - requestDigest, - tenantId, - 17, - sourceKey, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - NAMESPACE, - requestId, - operationId, - requestDigest, - tenantId, - 17, - sourceKey, - "NEW_GAME_ROW")); - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java deleted file mode 100644 index 6a57f07a05..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.firedevops.firemud.accountservice.security; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.grpc.Attributes; -import io.grpc.Context; -import io.grpc.Grpc; -import io.grpc.Metadata; -import io.grpc.MethodDescriptor; -import io.grpc.ServerCall; -import io.grpc.ServerCallHandler; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import javax.net.ssl.SSLSession; -import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; -import net.firedevops.firemud.account.v1.AccountServiceGrpc; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.SessionContext; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - -class AccountPlayerAdmissionEntitlementWorkloadGuardTest { - private final AccountPlayerAdmissionEntitlementWorkloadGuard guard = - new AccountPlayerAdmissionEntitlementWorkloadGuard("firemud"); - - @AfterEach - void clear() { - SessionContext.clear(); - } - - @Test - void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { - var method = - AccountPlayerAdmissionEntitlementReadServiceGrpc.getReadPlayerAdmissionEntitlementMethod(); - assertThat(invoke(method, tls("firemud", "game-session-service"))).isNull(); - assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) - .isInstanceOf(StatusRuntimeException.class); - assertThat(invoke(method, tls("other", "game-session-service")).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat(invoke(method, tls("firemud", "account-service")).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat( - invoke(AccountServiceGrpc.getGetProfileMethod(), tls("firemud", "game-session-service")) - .getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); - } - - @Test - void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { - var method = - AccountPlayerAdmissionEntitlementReadServiceGrpc.getReadPlayerAdmissionEntitlementMethod(); - Context.current() - .withValue( - GrpcPeerIdentity.CONTEXT_KEY, - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") - .orElseThrow()) - .run( - () -> { - assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); - assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) - .isInstanceOf(StatusRuntimeException.class); - }); - for (boolean internal : List.of(true, false)) { - if (internal) - SessionContext.setContext( - null, List.of(), Map.of(), true, "game-session-service", "instance"); - else SessionContext.setContext("caller", List.of(), Map.of()); - assertThat(invoke(method, tls("firemud", "game-session-service")).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); - SessionContext.clear(); - } - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private Status invoke(MethodDescriptor method, SSLSession ssl) { - ServerCall call = mock(ServerCall.class); - when(call.getMethodDescriptor()).thenReturn(method); - when(call.getAttributes()) - .thenReturn( - ssl == null - ? Attributes.EMPTY - : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); - AtomicInteger starts = new AtomicInteger(); - ServerCallHandler next = - (ignored, headers) -> { - assertThat(guard.requireAuthenticatedGameSessionCaller()) - .isEqualTo("spiffe://firemud/ns/firemud/sa/game-session-service"); - starts.incrementAndGet(); - return new ServerCall.Listener() {}; - }; - guard.interceptCall(call, new Metadata(), next); - var captured = ArgumentCaptor.forClass(Status.class); - verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); - assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); - return captured.getAllValues().isEmpty() ? null : captured.getValue(); - } - - private static SSLSession tls(String namespace, String service) throws Exception { - var leaf = mock(X509Certificate.class); - when(leaf.getSubjectAlternativeNames()) - .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); - var ssl = mock(SSLSession.class); - when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); - return ssl; - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java deleted file mode 100644 index 9e3654d9da..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ /dev/null @@ -1,941 +0,0 @@ -package unit.net.firedevops.firemud.accountservice.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import java.sql.Connection; -import java.time.Clock; -import java.time.Instant; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; -import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; -import net.firedevops.firemud.accountservice.repository.AccountHostingPlanQuote; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCurrentRecord; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; -import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; -import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; -import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -import org.jooq.ConnectionRunnable; -import org.jooq.DSLContext; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.SimpleTransactionStatus; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Controlled source doubles prove composition and denial, not authenticated custody or SQL locks. - */ -class AccountPlayerAdmissionEntitlementOwnerTest { - private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); - private static final String ISSUER = "firemud-account-service"; - private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; - private static final String PREFIX = "account:auth-authority:v1:"; - private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); - private static final String HASH = "a".repeat(64); - - @AfterEach - void clearTransactionFlags() { - TransactionSynchronizationManager.setActualTransactionActive(false); - TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); - } - - @Test - void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTarget() - throws Exception { - Fixture f = new Fixture(false); - var value = f.owner.evaluate(f.request, "controlled-token"); - assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); - assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); - assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); - assertThat(value.membershipSource().accountId()).isEqualTo(ACCOUNT.toString()); - assertThat(value.membershipSource().tenantId()).isEqualTo(TENANT.toString()); - assertThat(value.membershipSource().membershipExists()).isFalse(); - assertThat(value.membershipSource().membershipLifecycleState()).isEqualTo("MISSING"); - assertThat(value.membershipSource().gameplayAdmissionAllowed()).isFalse(); - assertThat(value.membershipSource().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); - assertThat(value.membershipSource().authorityTuple().accountAuthorityGeneration()) - .isEqualTo("1"); - assertThat(value.membershipSource().authorityTuple().membershipAuthorityGeneration()) - .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); - assertThat(value.fields()) - .containsEntry("verifiedConnectScopeId", f.scope.connectScopeId()) - .containsEntry("sourceKind", "NON_PAID_DEMO"); - var binding = (Map) value.fields().get("target"); - assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); - assertThat(binding.get("pointerVersion")).isEqualTo("3"); - assertThat(value.toString()).doesNotContain("controlled-token", f.scope.connectScopeId()); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); - verifyNoInteractions(f.hosting, f.observer); - } - - @Test - void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { - Fixture f = new Fixture(true); - var value = f.owner.evaluate(f.request, "controlled-token"); - assertThat(value.membershipSource().membershipExists()).isTrue(); - assertThat(value.membershipSource().membershipVersion()) - .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); - assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); - assertThat(value.membershipSource().sourceEvidence()) - .anySatisfy( - source -> { - assertThat(source.eventId()).isEqualTo("membership-event-1"); - assertThat(source.eventDigest()).startsWith("sha256:"); - }); - var order = inOrder(f.accounts, f.issuances, f.memberships, f.scopes, f.demos); - order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); - order.verify(f.issuances).readCurrentCommittedCandidateByJti(f.identity.tokenJti()); - order.verify(f.memberships).readCurrent(ACCOUNT, TENANT); - order.verify(f.scopes).findCanonical(f.scope.connectScopeId()); - order - .verify(f.scopes) - .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); - order.verify(f.demos).readCurrent(TENANT); - } - - @ParameterizedTest - @EnumSource(Status.class) - void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTransaction( - Status status) throws Exception { - Fixture f = new Fixture(true); - when(f.sources.readCurrentSourceSelection(TENANT)) - .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); - var fence = mock(ReadFence.class); - var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); - when(f.hosting.prepareCurrentRead(TENANT)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return fence; - }); - when(f.observer.observe(fence.binding())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return observed; - }); - when(f.hosting.readCurrent(fence, observed)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return f.receipt(status); - }); - var value = f.owner.evaluate(f.request, "controlled-token"); - assertThat(value.fields()) - .containsEntry("sourceKind", "PAID_HOSTING") - .containsEntry("subscriptionStatus", status.storageValue()) - .containsEntry("tenantBillingSequence", "1") - .containsEntry("tenantAuthorityGeneration", "2"); - boolean available = status != Status.SUSPENDED && status != Status.CANCELED; - assertThat(value.fields()) - .containsEntry("gameplayAvailable", available) - .containsEntry("allowPublicJoin", available && status != Status.GRACE) - .containsEntry("allowNewGameplayBindings", available && status != Status.GRACE) - .containsEntry("allowNewInstanceStarts", available && status != Status.GRACE); - assertThat(f.transactions.events) - .containsExactly("begin", "commit", "begin", "commit", "begin", "commit"); - var order = inOrder(f.observer, f.accounts, f.hosting); - order.verify(f.hosting).prepareCurrentRead(TENANT); - order.verify(f.observer).observe(fence.binding()); - order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); - order.verify(f.hosting).readCurrent(fence, observed); - } - - @Test - void scopeDeadlineReachedDuringFinalCommitReturnsNoValue() throws Exception { - Fixture f = new Fixture(false); - f.transactions.afterSecondCommit = () -> f.time.set(NOW.plusSeconds(60)); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("expired"); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); - } - - @Test - void callerAccountMismatchFailsBeforeAnySourceRead() throws Exception { - Fixture f = new Fixture(false); - var original = f.request.target(); - var other = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - original.readRequestId(), - UUID.randomUUID(), - original.targetNamespace(), - original.tenantId(), - original.tenantSlug(), - original.worldSlug(), - original.realmId(), - original.realmSlug(), - original.playableStateNamespaceId(), - original.playableStateScope(), - original.gameInstanceId(), - original.catalogRevision(), - original.pointerVersion()); - assertThatThrownBy( - () -> - f.owner.evaluate( - new Request(other, f.scope.connectScopeId(), PEER), "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions( - f.accounts, - f.issuances, - f.memberships, - f.scopes, - f.sources, - f.demos, - f.hosting, - f.observer, - f.targets); - } - - @Test - void unavailableOrChangedAccountSourceHeadNeverChoosesAnotherFamily() throws Exception { - Fixture f = new Fixture(false); - when(f.sources.readCurrentSourceSelection(TENANT)) - .thenThrow(new IllegalStateException("controlled missing source")); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("controlled missing source"); - verifyNoInteractions(f.demos, f.hosting, f.observer, f.targets); - - Fixture changed = new Fixture(false); - when(changed.sources.readCurrentSourceSelection(TENANT)) - .thenReturn( - new SourceSelection(SourceKind.NON_PAID_DEMO, changed.tenantEvent), - new SourceSelection(SourceKind.PAID_HOSTING, changed.tenantEvent)); - assertThatThrownBy(() -> changed.owner.evaluate(changed.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions(changed.demos, changed.hosting, changed.observer); - } - - @Test - void currentCallerLossDoesNotBecomeTenantOrBillingOwnerAuthority() throws Exception { - Fixture f = new Fixture(false); - when(f.issuances.readCurrentCommittedCandidateByJti(f.identity.tokenJti())) - .thenReturn(Optional.empty()); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions(f.memberships, f.scopes, f.demos, f.hosting, f.observer); - assertThat(f.transactions.events).containsExactly("begin", "rollback"); - } - - @Test - void absentCanonicalScopeRefusesPrivatePlaytestAndNumericScopeAliases() throws Exception { - Fixture f = new Fixture(false); - when(f.scopes.findCanonical(f.scope.connectScopeId())).thenReturn(Optional.empty()); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions(f.demos, f.hosting, f.observer); - } - - @Test - void anotherAccountsScopeFailsBeforeEntitlementCapture() throws Exception { - Fixture f = new Fixture(false); - when(f.scopes.findCanonicalEvidenceByTokenHash( - AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) - .thenReturn( - Optional.of(f.scopeEvidence(UUID.randomUUID(), f.scope.connectScopeExpiresAt()))); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions(f.demos); - } - - @Test - void expiredScopeDoesNotReturnCapturedAuthority() throws Exception { - Fixture f = new Fixture(false); - when(f.scopes.findCanonicalEvidenceByTokenHash( - AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) - .thenReturn(Optional.of(f.scopeEvidence(ACCOUNT, NOW.toString()))); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThat(f.transactions.events).containsExactly("begin", "commit"); - } - - @Test - void changedTenantCheckpointCannotBeCombinedWithAnOlderEntitlement() throws Exception { - Fixture f = new Fixture(false); - var original = f.demo; - var changed = - new DemoTenantEntitlementSnapshot( - TENANT, - f.source, - "NON_PAID_DEMO", - "ACTIVE", - null, - false, - true, - true, - true, - true, - original.quotas(), - 1, - 2, - 2, - original.outboxStreamKey(), - 1, - original.eventId(), - original.eventDigest(), - original.snapshotIdentity(), - original.tenantAuthorityOutboxStreamKey(), - 2, - original.tenantAuthorityEventId(), - original.tenantAuthorityEventDigest()); - when(f.demos.readCurrent(TENANT)).thenReturn(changed); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); - } - - @Test - void commitFailureReturnsNoEvidence() throws Exception { - Fixture f = new Fixture(false); - f.transactions.failCommit = true; - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("controlled commit failure"); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); - } - - @Test - void wrongWorkloadAndAmbientTransactionFailBeforeCallerOrSourceReads() throws Exception { - Fixture f = new Fixture(false); - Request wrongPeer = - new Request( - f.request.target(), - f.scope.connectScopeId(), - "spiffe://firemud/ns/other/sa/game-session-service"); - assertThatThrownBy(() -> f.owner.evaluate(wrongPeer, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions( - f.callers, - f.accounts, - f.issuances, - f.memberships, - f.scopes, - f.demos, - f.hosting, - f.observer); - } - - @Test - void unavailableProtectedTargetReturnsNoValueOrAlternateEntitlementSource() throws Exception { - Fixture f = new Fixture(false); - doThrow(new IllegalStateException("controlled target unavailable")) - .when(f.targets) - .resolvePublishedRealmAdmissionTarget(any()); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("controlled target unavailable"); - verifyNoInteractions(f.demos, f.hosting, f.observer); - assertThat(f.transactions.events).containsExactly("begin", "commit"); - } - - @Test - void changedOwnerPointerFailsExactRetainedTargetComparison() throws Exception { - Fixture f = new Fixture(false); - var selector = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - f.request.requestId(), - ACCOUNT, - "prod", - TENANT, - f.scope.tenantSlug(), - f.scope.worldSlug(), - f.scope.realmId(), - f.scope.realmSlug(), - f.scope.playableStateNamespaceId(), - "SHARED", - f.scope.gameInstanceId(), - f.scope.catalogRevision(), - f.scope.pointerVersion()); - var resolved = f.targets.resolvePublishedRealmAdmissionTarget(selector); - when(resolved.currentTarget().pointerVersion()).thenReturn(f.scope.pointerVersion() + 1); - doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("retained"); - verifyNoInteractions(f.demos, f.hosting, f.observer); - } - - @Test - void scopeChangedDuringProtectedTargetReadCannotBindFinalAccountEvidence() throws Exception { - Fixture f = new Fixture(false); - var original = f.scopeEvidence(ACCOUNT, f.scope.connectScopeExpiresAt()); - var changed = f.scopeEvidence(ACCOUNT, NOW.plusSeconds(50).toString()); - when(f.scopes.findCanonicalEvidenceByTokenHash( - AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) - .thenReturn(Optional.of(original), Optional.of(changed)); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - verifyNoInteractions(f.demos); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); - } - - @Test - void strictProtectedReadFailureNeverProducesCanonicalPlayerEvidence() throws Exception { - Fixture f = new Fixture(false); - var selector = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - f.request.requestId(), - ACCOUNT, - "prod", - TENANT, - f.scope.tenantSlug(), - f.scope.worldSlug(), - f.scope.realmId(), - f.scope.realmSlug(), - f.scope.playableStateNamespaceId(), - "SHARED", - f.scope.gameInstanceId(), - f.scope.catalogRevision(), - f.scope.pointerVersion()); - var resolved = f.targets.resolvePublishedRealmAdmissionTarget(selector); - when(f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())) - .thenThrow(new IllegalStateException("controlled World source stale")); - // Keep that exact resolver result so the strict-read denial cannot be replaced by new stubbing. - doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); - assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("controlled World source stale"); - verifyNoInteractions(f.demos, f.hosting, f.observer); - } - - /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ - private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { - when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - when(target.targetNamespace()).thenReturn(selector.targetNamespace()); - when(target.canonicalTenantId()).thenReturn(selector.tenantId()); - when(target.tenantSlug()).thenReturn(selector.tenantSlug()); - when(target.worldSlug()).thenReturn(selector.worldSlug()); - when(target.realmId()).thenReturn(selector.realmId()); - when(target.realmSlug()).thenReturn(selector.realmSlug()); - when(target.playableStateNamespaceId()) - .thenReturn(selector.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(selector.playableStateScope()); - when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); - when(target.catalogRevision()).thenReturn(selector.catalogRevision()); - when(target.pointerVersion()).thenReturn(selector.pointerVersion()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.ownerProofOutcome()) - .thenReturn( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); - UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); - when(target.canonicalVersionId()).thenReturn(version); - when(target.activeWorldEpoch()).thenReturn(5L); - var strict = - new CanonicalGameplayRosterOwnerReadEvidence.Request( - selector.readRequestId(), - selector.accountId(), - selector.targetNamespace(), - selector.tenantId(), - selector.worldSlug(), - selector.realmId(), - selector.realmSlug(), - selector.playableStateNamespaceId(), - selector.playableStateScope(), - selector.gameInstanceId(), - version, - selector.catalogRevision(), - selector.pointerVersion(), - 5L); - var resolved = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget - .class); - when(resolved.selector()).thenReturn(selector); - when(resolved.currentTarget()).thenReturn(target); - when(resolved.strictSelector()).thenReturn(strict); - var read = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - when(read.selector()).thenReturn(strict); - when(read.currentTarget()).thenReturn(target); - var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); - when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); - var policies = mock(PublishedRealmEntryPolicySetEvidence.class); - when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); - when(source.publishedPolicySetEvidence()).thenReturn(policies); - var ownerProof = - mock( - net.firedevops.firemud.common.world - .GameSessionCanonicalInitialAdmissionOwnerProof.class); - when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); - when(source.gameSessionOwnerProof()).thenReturn(ownerProof); - when(read.sourceEvidence()).thenReturn(source); - var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(world.canonicalBytes()) - .thenReturn( - "controlled-complete-world-source" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(world.captureId()) - .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); - when(world.rowVersion()).thenReturn(2L); - when(read.worldLifecycleEvidence()).thenReturn(world); - when(targets.readPublishedRealmAdmissionOwner(strict)) - .thenAnswer( - readCall -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return read; - }); - return resolved; - }); - } - - private static final class Fixture { - private final AccountRepository accounts = mock(AccountRepository.class); - private final AccountGameplayAdmissionCallerVerifier callers = - mock(AccountGameplayAdmissionCallerVerifier.class); - private final AccountGameplayDelegationIssuanceRepository issuances = - mock(AccountGameplayDelegationIssuanceRepository.class); - private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = - mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); - private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); - private final AccountHostingSubscriptionLifecycleRepository hosting = - mock(AccountHostingSubscriptionLifecycleRepository.class); - private final StripeHostingSubscriptionObserver observer = - mock(StripeHostingSubscriptionObserver.class); - private final AccountDemoTenantEntitlementRepository demos = - mock(AccountDemoTenantEntitlementRepository.class); - private final AccountTenantAuthorityEventRepository sources = - mock(AccountTenantAuthorityEventRepository.class); - private final CanonicalGameplayAdmissionDecisionReadClient targets = - mock(CanonicalGameplayAdmissionDecisionReadClient.class); - private final RecordingTransactions transactions = new RecordingTransactions(); - private final java.util.concurrent.atomic.AtomicReference time = - new java.util.concurrent.atomic.AtomicReference<>(NOW); - private final FreshTenantCreationEvidence source = source(); - private final TenantAuthorityEventV1Codec.Event tenantEvent = tenantEvent(source); - private final CanonicalJoinScopeV2 scope = - new CanonicalJoinScopeV2( - "private-bearer-" + UUID.randomUUID(), - ACCOUNT, - TENANT, - UUID.randomUUID(), - "tenant", - "world", - "production", - UUID.randomUUID(), - "SHARED", - UUID.randomUUID(), - 7, - 3, - NOW.minusSeconds(20).toString(), - NOW.plusSeconds(60).toString()); - private final AccountGameplayDelegationPendingIdentity identity = - new AccountGameplayDelegationPendingIdentity( - UUID.randomUUID(), - UUID.randomUUID(), - ACCOUNT, - PEER, - UUID.randomUUID(), - mock(AccountGameplayCredentialRequestBinding.class), - HASH, - UUID.randomUUID(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond()); - private final DemoTenantEntitlementSnapshot demo = - new DemoTenantEntitlementSnapshot( - TENANT, - source, - "NON_PAID_DEMO", - "ACTIVE", - null, - false, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 2, 4096), - 1, - 2, - 2, - tenantEvent.tenantBillingStreamKey(), - 1, - tenantEvent.tenantBillingEventId(), - tenantEvent.tenantBillingEventDigest(), - tenantEvent.tenantBillingEventDigest(), - tenantEvent.outboxStreamKey(), - 1, - tenantEvent.eventId(), - tenantEvent.eventDigest()); - private final Request request = - new Request( - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - UUID.randomUUID(), - ACCOUNT, - "prod", - TENANT, - scope.tenantSlug(), - scope.worldSlug(), - scope.realmId(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion()), - scope.connectScopeId(), - PEER); - private final AccountPlayerAdmissionEntitlementOwner owner; - - private Fixture(boolean exists) throws Exception { - controlledTarget(targets); - var dsl = mock(DSLContext.class); - var connection = mock(Connection.class); - when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); - doAnswer( - invocation -> { - invocation.getArgument(0, ConnectionRunnable.class).run(connection); - return null; - }) - .when(dsl) - .connection(any(ConnectionRunnable.class)); - var candidate = mock(CommittedCandidateVerificationData.class); - when(candidate.identity()).thenReturn(identity); - when(candidate.authoritySnapshot()) - .thenReturn(new AccountAuthoritySnapshot(ACCOUNT, 1, 1, 1, 1, 1, 1, Optional.empty())); - when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); - when(candidate.signerCorrespondence()) - .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); - when(candidate.tokenSha256()).thenReturn(HASH); - when(candidate.signerKid()).thenReturn("controlled-kid"); - when(candidate.signerGeneration()).thenReturn("1"); - when(candidate.canonicalRegistryRecordSha256()).thenReturn(HASH); - when(candidate.commitProofSha256()).thenReturn(HASH); - when(candidate.envelopeKeyId()).thenReturn("controlled-envelope-key"); - when(candidate.envelopeSha256()).thenReturn(HASH); - var caller = mock(VerifiedCaller.class); - when(caller.identity()).thenReturn(identity); - when(caller.currentCandidate()).thenReturn(candidate); - when(callers.verifyPresentedCompactToken("controlled-token")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return caller; - }); - Account account = new Account(); - account.setId(10L); - account.setAccountUuid(ACCOUNT); - when(accounts.findByAccountUuidForUpdate(ACCOUNT)).thenReturn(Optional.of(account)); - when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) - .thenReturn(Optional.of(candidate)); - when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(snapshot(exists)); - when(scopes.findCanonical(scope.connectScopeId())).thenReturn(Optional.of(scope)); - when(scopes.findCanonicalEvidenceByTokenHash( - AccountJoinDigest.tokenHash(scope.connectScopeId()))) - .thenReturn(Optional.of(scopeEvidence(ACCOUNT, scope.connectScopeExpiresAt()))); - when(demos.readCurrent(TENANT)).thenReturn(demo); - when(sources.readCurrentSourceSelection(TENANT)) - .thenReturn(new SourceSelection(SourceKind.NON_PAID_DEMO, tenantEvent)); - Clock clock = mock(Clock.class); - when(clock.instant()).thenAnswer(invocation -> time.get()); - owner = - new AccountPlayerAdmissionEntitlementOwner( - dsl, - accounts, - callers, - issuances, - memberships, - scopes, - hosting, - observer, - demos, - sources, - targets, - transactions, - clock, - "prod"); - } - - private CanonicalConnectScopeEvidence scopeEvidence(UUID account, String expiry) { - return new CanonicalConnectScopeEvidence( - AccountJoinDigest.tokenHash(scope.connectScopeId()), - 10, - "PUBLIC_PRODUCTION", - account, - TENANT, - scope.realmId(), - scope.tenantSlug(), - scope.worldSlug(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion(), - scope.evaluatedAt(), - expiry, - 2, - AccountJoinDigest.scopeV2(scope), - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - source.operationId(), - source.evidenceDigest())); - } - - private AccountHostingSubscriptionCurrentReceipt receipt(Status status) { - var current = mock(AccountSubscriptionCurrentRecord.class); - when(current.tenantId()).thenReturn(TENANT); - when(current.subscriptionId()).thenReturn(UUID.randomUUID()); - when(current.rowVersion()).thenReturn(2L); - when(current.planQuote()) - .thenReturn(new AccountHostingPlanQuote("standard", "price_Test", 1, 3, 2, 4096)); - return new AccountHostingSubscriptionCurrentReceipt( - current, - UUID.randomUUID(), - status, - status != Status.SUSPENDED && status != Status.CANCELED, - status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, - status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, - status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, - 1, - 1, - tenantEvent.tenantBillingEventId(), - tenantEvent.tenantBillingEventDigest(), - tenantEvent, - "active", - NOW.minusSeconds(100), - NOW.plusSeconds(1000), - false, - null, - null, - NOW, - NOW.plusSeconds(60)); - } - - private Snapshot snapshot(boolean exists) { - var cutoff = new TenantBillingCutoff("2", "1", tenantEvent.outboxStreamKey(), "1"); - var tuple = - new AuthorityTuple( - "1", - "1", - Map.of(TENANT.toString(), "2"), - Map.of(TENANT.toString(), "1"), - List.of(), - Optional.empty(), - Optional.of(Map.of(TENANT.toString(), cutoff))); - List events = new ArrayList<>(); - if (exists) { - Map event = new LinkedHashMap<>(); - event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); - event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); - event.put("eventId", "membership-event-1"); - event.put("requestId", "membership-request-1"); - event.put("outboxStreamKey", memberStream()); - event.put("outboxSequence", "1"); - event.put("sourceScope", "membership/" + ACCOUNT + "/" + TENANT); - event.put("accountId", ACCOUNT.toString()); - event.put("tenantId", TENANT.toString()); - event.put("membershipExists", true); - event.put("membershipLifecycleState", "ACTIVE"); - event.put("membershipVersion", Map.of(TENANT.toString(), "1")); - event.put("membershipAuthorityGeneration", "1"); - event.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", - "1", - "accountAuthorityGeneration", - "1", - "tenantAuthorityGeneration", - Map.of(TENANT.toString(), "2"), - "membershipAuthorityGeneration", - Map.of(TENANT.toString(), "1"), - "privateRealmGrantVersions", - List.of(), - "tenantBillingCutoff", - Map.of( - TENANT.toString(), - Map.of( - "tenantAuthorityGeneration", - "2", - "tenantBillingSequence", - "1", - "outboxStreamKey", - tenantEvent.outboxStreamKey(), - "outboxSequence", - "1")))); - event.put("issuanceFence", "1"); - event.put("roles", List.of("player")); - event.put("gameplayAdmissionAllowed", true); - event.put("callerBoundAuthorityInvalidated", false); - var sealed = MembershipAuthorityEventV1Codec.seal(event); - events.add( - new SourceEvidence( - memberStream(), - "1", - sealed.eventId(), - sealed.eventDigest(), - sealed.canonicalJson())); - } - events.add( - new SourceEvidence( - tenantEvent.outboxStreamKey(), - "1", - tenantEvent.eventId().toString(), - tenantEvent.eventDigest(), - new String(tenantEvent.payload(), java.nio.charset.StandardCharsets.UTF_8))); - return new Snapshot( - ISSUER, - ACCOUNT.toString(), - TENANT.toString(), - exists, - exists ? "ACTIVE" : "MISSING", - exists, - Map.of(TENANT.toString(), "1"), - "1", - exists ? List.of("player") : List.of(), - tuple, - "1", - List.of( - new Checkpoint(PREFIX + "account/" + ACCOUNT, "0"), - new Checkpoint(PREFIX + "issuer/" + ISSUER, "0"), - new Checkpoint(memberStream(), exists ? "1" : "0"), - new Checkpoint(tenantEvent.outboxStreamKey(), "1")), - events); - } - } - - private static String memberStream() { - return PREFIX + "membership/" + ACCOUNT + "/" + TENANT; - } - - private static FreshTenantCreationEvidence source() { - UUID requestId = UUID.randomUUID(); - UUID operationId = UUID.randomUUID(); - String requestDigest = - GameTenantCreationDigest.requestDigest("prod", requestId, "world", "World", null); - return new FreshTenantCreationEvidence( - 1, - "prod", - requestId, - operationId, - requestDigest, - TENANT, - 17, - "world", - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - "prod", requestId, operationId, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); - } - - private static TenantAuthorityEventV1Codec.Event tenantEvent(FreshTenantCreationEvidence source) { - UUID requestId = UUID.randomUUID(); - var request = - new TenantAuthorityEventV1Codec.AuthorityRequest( - requestId, - "sha256:" + HASH, - TENANT, - source.creationRequestId(), - source.requestDigest()); - var receipt = - new TenantAuthorityEventV1Codec.BillingReceipt( - TENANT, - requestId, - "sha256:" + HASH, - TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), - 1, - TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), - "sha256:" + HASH); - return TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, receipt); - } - - private static final class RecordingTransactions implements PlatformTransactionManager { - private final List events = new ArrayList<>(); - private boolean failCommit; - private Runnable afterSecondCommit = () -> {}; - - @Override - public TransactionStatus getTransaction( - @org.jspecify.annotations.Nullable TransactionDefinition definition) { - if (definition != null) { - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); - assertThat(definition.isReadOnly()).isFalse(); - } - events.add("begin"); - TransactionSynchronizationManager.setActualTransactionActive(true); - return new SimpleTransactionStatus(); - } - - @Override - public void commit(TransactionStatus status) { - events.add("commit"); - TransactionSynchronizationManager.setActualTransactionActive(false); - if (events.size() == 4) afterSecondCommit.run(); - if (failCommit && events.size() == 4) - throw new IllegalStateException("controlled commit failure"); - } - - @Override - public void rollback(TransactionStatus status) { - events.add("rollback"); - TransactionSynchronizationManager.setActualTransactionActive(false); - } - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java deleted file mode 100644 index ce61e144dd..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.firedevops.firemud.accountservice.service.impl; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -import io.grpc.Status; -import io.grpc.stub.StreamObserver; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; -import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - -/** Direct method calls cannot install the receiver's TLS-derived private peer assertion. */ -class AccountPlayerAdmissionEntitlementGrpcServiceTest { - @Test - @SuppressWarnings("unchecked") - void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() { - var owner = mock(AccountPlayerAdmissionEntitlementOwner.class); - var service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); - for (var request : - new ReadPlayerAdmissionEntitlementRequest[] { - null, - ReadPlayerAdmissionEntitlementRequest.getDefaultInstance(), - ReadPlayerAdmissionEntitlementRequest.newBuilder() - .addInitialLoginJwt("private-token".repeat(4000)) - .build() - }) { - StreamObserver observer = mock(StreamObserver.class); - - service.readPlayerAdmissionEntitlement(request, observer); - - var failure = ArgumentCaptor.forClass(Throwable.class); - verify(observer).onError(failure.capture()); - assertThat(Status.fromThrowable(failure.getValue()).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED); - assertThat(failure.getValue().getMessage()).doesNotContain("private-token"); - verify(observer, never()).onNext(any()); - verify(observer, never()).onCompleted(); - } - verifyNoInteractions(owner); - } -} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index c08602aa0a..14e01a13bd 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -27,7 +27,6 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; /** * Genuine Account owner mutations. Fresh creator/legal sources and signer platform evidence are @@ -101,35 +100,6 @@ public AccountControlUiOriginalOrderFixture( ownedCompositionConnections); } - /** - * Test-only composition with one preselected Game Design provenance tuple shared by Account and - * World. It is imported during construction, never substituted onto existing associations. - */ - public AccountControlUiOriginalOrderFixture( - String jdbcUrl, - String username, - String password, - String redisHost, - int redisPort, - Path temporary, - FreshTenantCreationEvidence creationEvidence, - boolean ownedCompositionConnections) - throws Exception { - this( - jdbcUrl, - username, - password, - redisHost, - redisPort, - temporary, - Objects.requireNonNull(creationEvidence, "creationEvidence").canonicalTenantId(), - Clock.systemUTC(), - null, - Clock.systemUTC(), - ownedCompositionConnections, - creationEvidence); - } - /** Actor clock is injectable for genuine signed-credential expiry recovery proof. */ public AccountControlUiOriginalOrderFixture( String jdbcUrl, @@ -223,35 +193,6 @@ private AccountControlUiOriginalOrderFixture( Clock serviceClock, boolean ownedCompositionConnections) throws Exception { - this( - jdbcUrl, - username, - password, - redisHost, - redisPort, - temporary, - gameDesignTenant, - actorClock, - migrationTarget, - serviceClock, - ownedCompositionConnections, - AccountControlUiOwnerSourcesFixture.defaultCreation(gameDesignTenant)); - } - - private AccountControlUiOriginalOrderFixture( - String jdbcUrl, - String username, - String password, - String redisHost, - int redisPort, - Path temporary, - UUID gameDesignTenant, - Clock actorClock, - String migrationTarget, - Clock serviceClock, - boolean ownedCompositionConnections, - FreshTenantCreationEvidence creationEvidence) - throws Exception { this.temporary = temporary; Objects.requireNonNull(actorClock, "actorClock"); Objects.requireNonNull(serviceClock, "serviceClock"); @@ -264,8 +205,7 @@ private AccountControlUiOriginalOrderFixture( false, gameDesignTenant, migrationTarget, - ownedCompositionConnections, - creationEvidence); + ownedCompositionConnections); RedisClient allocatedClient = null; try { signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); @@ -295,8 +235,6 @@ private AccountControlUiOriginalOrderFixture( .on() .addPassword(PASSWORD) .keyPattern("session:auth:token:*") - .keyPattern("session:auth:generation:issuer:*") - .keyPattern("session:auth:generation:account:*") .addCommand(io.lettuce.core.protocol.CommandType.HELLO) .addCommand(io.lettuce.core.protocol.CommandType.PING) .addCommand( @@ -312,8 +250,6 @@ private AccountControlUiOriginalOrderFixture( .addCommand(io.lettuce.core.protocol.CommandType.GET) .addCommand(io.lettuce.core.protocol.CommandType.SET) .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) - .addCommand(io.lettuce.core.protocol.CommandType.PTTL) - .addCommand(io.lettuce.core.protocol.CommandType.TYPE) .addCommand(io.lettuce.core.protocol.CommandType.TIME)); connection .sync() @@ -399,16 +335,6 @@ public UUID tenantId() { return f.tenant; } - /** The exact immutable source tuple imported at construction for cross-owner composition. */ - public FreshTenantCreationEvidence creationEvidence() { - return f.creationEvidence; - } - - /** Reuse the same physical test-only Account writer without resetting its ACL or credentials. */ - AccountCoordinationPinnedConnectionProvider gameplayConnectionProvider() { - return () -> accountClient.connect(ByteArrayCodec.INSTANCE); - } - /** * Real Account-owned selected Game Logic source reads over this fixture's SQL and Coordination * Redis owners; callers choose the clock and target namespace for their composition. diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index f6f082f13d..3f2a920a59 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -99,7 +99,6 @@ final class AccountControlUiOwnerSourcesFixture { final Account account; final AccountRepository accounts; final UUID tenant; - final FreshTenantCreationEvidence creationEvidence; final UUID request = UUID.randomUUID(), callerContext = UUID.randomUUID(); final AtomicReference boundary = new AtomicReference<>(testBoundary("test-production")); @@ -163,35 +162,6 @@ final class AccountControlUiOwnerSourcesFixture { String migrationTarget, boolean ownedCompositionConnections) throws Exception { - this( - jdbcUrl, - username, - password, - root, - installNegativeIssuer, - tenant, - migrationTarget, - ownedCompositionConnections, - defaultCreation(tenant)); - } - - /** Shared immutable provenance must be supplied before any Account association is created. */ - AccountControlUiOwnerSourcesFixture( - String jdbcUrl, - String username, - String password, - Path root, - boolean installNegativeIssuer, - UUID tenant, - String migrationTarget, - boolean ownedCompositionConnections, - FreshTenantCreationEvidence creationEvidence) - throws Exception { - this.creationEvidence = Objects.requireNonNull(creationEvidence, "creationEvidence"); - if (!creationEvidence.canonicalTenantId().equals(tenant)) { - throw new IllegalArgumentException( - "Shared creation evidence must identify the Account tenant"); - } if (migrationTarget != null && !HISTORICAL_MIGRATION_TARGETS.contains(migrationTarget)) { throw new IllegalArgumentException( "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); @@ -237,9 +207,8 @@ final class AccountControlUiOwnerSourcesFixture { candidate.setLoginAuthModes("EMAIL_OTP"); return accounts.save(candidate); }); - var creator = testCreation(account.getAccountUuid(), creationEvidence); - var fresh = - new FreshTenantIdentityAssociationRepository(dsl, creationEvidence.targetNamespace()); + var creator = testCreation(account.getAccountUuid(), tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); tx( () -> { fresh.importVerified(creator.creationEvidence()); @@ -700,28 +669,26 @@ void assertNoIssuance() { assertThat(coordinationCalls).hasValue(0); } - static FreshTenantCreationEvidence defaultCreation(UUID tenant) { - UUID request = UUID.randomUUID(), operation = UUID.randomUUID(); + private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { + UUID request = UUID.randomUUID(), + operation = UUID.randomUUID(), + authorization = UUID.randomUUID(); String key = "test-only-game-row-17"; String digest = GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); - return new FreshTenantCreationEvidence( - 1, - NAMESPACE, - request, - operation, - digest, - tenant, - 17L, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); - } - - private static FreshTenantCreatorEvidence testCreation( - UUID account, FreshTenantCreationEvidence creation) { - UUID authorization = UUID.randomUUID(); + var creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); String authorizationDigest = "sha256:" + "8".repeat(64); return new FreshTenantCreatorEvidence( 1, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java deleted file mode 100644 index 0040681212..0000000000 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java +++ /dev/null @@ -1,559 +0,0 @@ -package net.firedevops.firemud.accountservice.service.session; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoInteractions; - -import io.grpc.Context; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.security.SecureRandom; -import java.time.Clock; -import java.time.Instant; -import java.util.Arrays; -import java.util.Base64; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.config.AccountTokenProperties; -import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; -import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; -import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; -import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; -import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; -import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; -import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; -import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner.RealmScope; -import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; -import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; -import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; -import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; -import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; -import org.springframework.transaction.interceptor.TransactionInterceptor; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Separate global-player composition over the original Account database and real protected target - * client. Repository insertion, absence enrollment, DEMO provisioning, LOGIN/currentness, canonical - * scope production and the entitlement receiver use their actual owners. The player has no tenant - * membership, no roles and no admission permission until the explicit first-JOIN method runs; the - * original creator is never rewritten. - * - *

Construct only after the original creator/operator authoring sequence is finished: DEMO - * advances tenant authority, which deliberately makes the creator's historical baseline unsuitable - * for current runtime membership evidence. Scope peer/context custody, demo policy, enrollment/OTP - * delivery and test signing-key custody remain controlled. Paid and browser-only dependencies fail - * on every call and cannot supply successful evidence. This helper borrows connections, registers - * no runtime beans, opens no listener and claims no public ingress, World hold or PLAY authority. - * Its optional first JOIN proves only Account-local atomic membership/event/audit/receipt - * ownership. - */ -public final class AccountPlayerAdmissionSharedEntitlementFixture { - private static final SecureRandom RANDOM = new SecureRandom(); - private final AccountControlUiOwnerSourcesFixture sources; - private final AccountPlayerAdmissionSharedOwnerFixture login; - private final AccountCanonicalRuntimeMembershipSnapshotRepository snapshots; - private final AccountDemoTenantEntitlementRepository demos; - private final DemoTenantEntitlementSnapshot demo; - private final AccountCanonicalPublicRealmScopeOwner scopes; - private final AccountCanonicalConnectScopeReader scopeReader; - private final CanonicalGameplayAdmissionDecisionReadClient targets; - private final AccountAuthoritySourceEvidenceRepository authority; - private final AccountAuthorityOutboxRepository outbox; - private final AccountTenantMembershipRepository members; - private final AccountMembershipPairAuthorityRepository pairs; - private final AccountJoinOperationRepository operations; - private final AccountAuditOutboxRepository audits; - private final AccountCanonicalFirstJoinTerminalCoordinator firstJoin; - private final TransactionTemplate joinTransaction; - private final AccountPlayerAdmissionEntitlementGrpcService receiver; - private final AccountHostingSubscriptionLifecycleRepository unusedPaidRepository; - private final StripeHostingSubscriptionObserver unusedProvider; - private final SessionService unusedBrowserSessions; - private final Clock clock; - private final String namespace; - - public AccountPlayerAdmissionSharedEntitlementFixture( - AccountControlUiOriginalOrderFixture original, - Path temporary, - CanonicalGameplayAdmissionDecisionReadClient genuineTargets, - DemoTenantEntitlementRequest demoRequest) - throws Exception { - this(original, temporary, genuineTargets, demoRequest, Clock.systemUTC()); - } - - public AccountPlayerAdmissionSharedEntitlementFixture( - AccountControlUiOriginalOrderFixture original, - Path temporary, - CanonicalGameplayAdmissionDecisionReadClient genuineTargets, - DemoTenantEntitlementRequest demoRequest, - Clock clock) - throws Exception { - Objects.requireNonNull(original, "Original Account fixture is required"); - targets = - Objects.requireNonNull( - genuineTargets, "Actual initialized protected target client is required"); - this.clock = Objects.requireNonNull(clock, "Clock is required"); - FreshTenantCreationEvidence creation = original.creationEvidence(); - requireFirstDemoRequest(demoRequest, creation); - namespace = creation.targetNamespace(); - sources = original.preparedOriginalCreator().sources(); - login = AccountPlayerAdmissionSharedOwnerFixture.freshGlobalPlayer(original, temporary, clock); - - var generations = new AccountAuthorityGenerationRepository(sources.dsl); - outbox = new AccountAuthorityOutboxRepository(sources.dsl); - authority = new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); - var fresh = new FreshTenantIdentityAssociationRepository(sources.dsl, namespace); - pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); - members = new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); - var roles = new AccountTenantMembershipRoleSnapshotRepository(sources.dsl); - var billing = new AccountTenantEntitlementOutboxRepository(sources.dsl); - var tenantEvents = - new AccountTenantAuthorityEventRepository(sources.dsl, outbox, billing, fresh, generations); - demos = - new AccountDemoTenantEntitlementRepository( - sources.dsl, fresh, generations, billing, tenantEvents); - snapshots = - new AccountCanonicalRuntimeMembershipSnapshotRepository( - sources.accounts, - generations, - authority, - tenantEvents, - fresh, - members, - pairs, - roles, - outbox); - // Missing rows alone are not evidence. Enroll the exact account-fenced absence baseline. - demo = - sources.tx( - () -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - generations.initialize(AuthorityScope.membership(login.accountId(), sources.tenant)); - members.prepareFreshCreatorAbsence(login.accountId(), sources.tenant); - return demos.provision(demoRequest, creation); - }); - - var retainedScopes = - new AccountConnectScopeRepository( - sources.dsl, - new AccountTenantIdentityResolver( - new ApprovedLegacyTenantAssociationRepository( - sources.dsl, new LegacyTenantSourceEvidence(sources.dsl), namespace), - namespace), - fresh); - unusedPaidRepository = excluded(AccountHostingSubscriptionLifecycleRepository.class); - unusedProvider = excluded(StripeHostingSubscriptionObserver.class); - unusedBrowserSessions = excluded(SessionService.class); - var hosting = - new AccountHostingSubscriptionLifecycleService( - unusedPaidRepository, unusedProvider, sources.manager); - var publicEntitlements = - new AccountPublicBootstrapEntitlementOwner( - tenantEvents, hosting, demos, sources.manager, clock); - var tokens = new AccountTokenProperties(); - var jwt = new JwtUtil(scopeSigningKey(), tokens.getConnectScopeExpirationMs()); - scopeReader = - new AccountCanonicalConnectScopeReader(jwt, retainedScopes, sources.manager, clock); - operations = new AccountJoinOperationRepository(sources.dsl, retainedScopes); - audits = new AccountAuditOutboxRepository(sources.dsl); - var membershipEvents = - transactional( - new AccountMembershipAuthorityEventProducer( - operations, - sources.accounts, - pairs, - members, - roles, - generations, - outbox, - authority, - tenantEvents, - demos), - AccountMembershipAuthorityEventProducer.class); - firstJoin = - transactional( - new AccountCanonicalFirstJoinTerminalCoordinator( - sources.accounts, - operations, - members, - roles, - outbox, - pairs, - audits, - membershipEvents), - AccountCanonicalFirstJoinTerminalCoordinator.class); - joinTransaction = new TransactionTemplate(sources.manager); - joinTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - joinTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - joinTransaction.setReadOnly(false); - scopes = - new AccountCanonicalPublicRealmScopeOwner( - new AccountPlayerBootstrapCallerVerifier(jwt, sources.accounts, unusedBrowserSessions), - genuineTargets, - publicEntitlements, - sources.accounts, - members, - fresh, - tenantEvents, - retainedScopes, - jwt, - tokens, - clock, - sources.manager, - namespace); - var owner = - new AccountPlayerAdmissionEntitlementOwner( - sources.dsl, - sources.accounts, - login.admissionCallerVerifier(), - login.issuanceRepository(), - snapshots, - retainedScopes, - unusedPaidRepository, - unusedProvider, - demos, - tenantEvents, - genuineTargets, - sources.manager, - clock, - namespace); - receiver = new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); - assertAbsentMembership(); - } - - public AccountPlayerAdmissionSharedOwnerFixture login() { - return login; - } - - public AccountJwtJwksTrustedSource trustedJwksSource() { - return login.trustedJwksSource(); - } - - /** The receiver creates only an explicit private mTLS listener when its caller requests one. */ - public AccountPlayerAdmissionEntitlementGrpcService receiver() { - return receiver; - } - - /** - * Uses the real scope owner, signed token, retained readback and protected target client. Only - * this scope-invocation peer is stipulated; no authenticated socket or public ingress is proved. - */ - public RealmScope issueScopeWithControlledGameSessionCaller( - DirectTextCallerContext caller, DirectTextJoinTarget target) { - Objects.requireNonNull(caller, "Controlled direct-text caller is required"); - Objects.requireNonNull(target, "Actual selected target is required"); - if (!login.accountId().equals(caller.accountId()) - || !sources.tenant.equals(caller.tenantId()) - || !sources.tenant.equals(target.tenantId())) { - throw new IllegalArgumentException("Scope must use the separate player and shared tenant"); - } - var peer = - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/game-session-service") - .orElseThrow(); - Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); - Context previous = context.attach(); - try { - RealmScope result = scopes.issueDirectTextScope(caller, target); - assertThat(result.membership().accountId()).isEqualTo(login.accountId()); - assertThat(result.membership().tenantId()).isEqualTo(sources.tenant); - assertThat(result.membership().current()).isEmpty(); - assertThat(result.entitlement().sourceKind()).isEqualTo(SourceKind.NON_PAID_DEMO); - assertThat(result.entitlement().entitlementVersion()).isEqualTo(demo.entitlementVersion()); - assertAbsentMembership(); - return result; - } finally { - context.detach(previous); - } - } - - /** - * Explicit owner-local first JOIN. Request and caller binding are controlled correlation inputs, - * not authentication supplied by this coordinator. Signed scope/current target checks precede - * SQL; they establish no cross-service hold through commit. Replay uses the identical inputs. - */ - public CanonicalJoinTerminalProof commitFirstJoin( - RealmScope issued, String requestId, String controlledCallerBinding) { - Objects.requireNonNull(issued, "Actual issued realm scope is required"); - var scope = scopeReader.read(login.accountId(), issued.scope().connectScopeId()); - assertThat(scope).isEqualTo(issued.scope()); - assertThat(scope.tenantId()).isEqualTo(sources.tenant); - requireCurrentTarget(issued, scope); - var before = - joinTransaction.execute( - status -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding); - return authority.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, login.accountId()); - }); - // The second actual target read detects pre-commit drift, but is intentionally not a hold. - requireCurrentTarget(issued, scope); - CanonicalJoinTerminalProof proof = - joinTransaction.execute( - status -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - requireLiveScope(scope); - var currentDemo = demos.revalidate(demo); - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - controlledCallerBinding, - currentDemo.allowPublicJoin(), - currentDemo.entitlementVersion()); - var committed = - firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); - assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, committed); - requireLiveScope(scope); - return committed; - }); - Objects.requireNonNull(proof, "Committed first-JOIN receipt is required"); - // Independent transaction proves durable terminal replay, not merely same-transaction reads. - var replay = - joinTransaction.execute( - status -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - requireLiveScope(scope); - assertThat( - operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding)) - .isFalse(); - var repeated = - firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); - assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, repeated); - return repeated; - }); - assertThat(replay).isEqualTo(proof); - assertThat(scopeReader.read(login.accountId(), scope.connectScopeId())).isEqualTo(scope); - var after = - sources.tx( - () -> - authority.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, login.accountId())); - Objects.requireNonNull(before, "Original LOGIN authority sources are required"); - assertThat(after.issuer()).isEqualTo(before.issuer()); - assertThat(after.account()).isEqualTo(before.account()); - assertThat(after.issuanceFence()).isEqualTo(before.issuanceFence()); - login.assertCreatorRemainsNonAdmitting(); - verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); - return proof; - } - - /** Positive membership source evidence only, after the same real receiver/client reread. */ - public void assertAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence evidence) { - Objects.requireNonNull(evidence, "Actual Account receiver evidence is required"); - evidence.requireCurrentAt(clock.instant()); - var current = sources.tx(() -> snapshots.readCurrent(login.accountId(), sources.tenant)); - assertThat(evidence.membershipSource()).isEqualTo(current); - assertAdmittingSnapshot(current); - sources.tx(() -> demos.revalidate(demo)); - login.assertCreatorRemainsNonAdmitting(); - verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); - } - - private void requireCurrentTarget(RealmScope issued, CanonicalJoinScopeV2 scope) { - var selector = - new RetainedTargetSelector( - UUID.randomUUID(), - scope.accountId(), - namespace, - scope.tenantId(), - scope.tenantSlug(), - scope.worldSlug(), - scope.realmId(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion()); - var resolved = targets.resolvePublishedRealmAdmissionTarget(selector); - CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( - selector, resolved.currentTarget()); - assertThat(resolved.selector()).isEqualTo(selector); - var current = targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); - assertThat(current.selector()).isEqualTo(resolved.strictSelector()); - assertThat(current.currentTarget()) - .isEqualTo(resolved.currentTarget()) - .isEqualTo(issued.target()); - requireLiveScope(scope); - } - - private void requireLiveScope(CanonicalJoinScopeV2 scope) { - Instant now = clock.instant(); - if (now.isBefore(Instant.parse(scope.evaluatedAt())) - || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) { - throw new IllegalStateException("Original signed first-JOIN scope is no longer current"); - } - } - - /** All rows are read beneath the same Account fence as the actual terminal owner. */ - private void assertFirstJoinReceipt( - CanonicalJoinScopeV2 scope, - String requestId, - String callerBinding, - CanonicalJoinTerminalProof proof) { - var operation = operations.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); - assertThat(operation.status()).isEqualTo("COMMITTED"); - assertThat(operation.outcome()).isEqualTo("JOINED"); - assertThat(operation.callerBinding()).isEqualTo(callerBinding); - assertThat(operation.scopeTokenHash()) - .isEqualTo(AccountJoinDigest.tokenHash(scope.connectScopeId())); - assertThat(operation.connectScopeDigest()).isEqualTo(AccountJoinDigest.scopeV2(scope)); - assertThat(operation.intentDigest()) - .isEqualTo(AccountJoinDigest.intentV2(requestId, scope, callerBinding)); - assertThat(operation.terminalProof()).isEqualTo(proof); - assertThat(proof.entitlementVersion()).isEqualTo(demo.entitlementVersion()); - assertThat(proof.membershipVersion()).isEqualTo(2L); - assertThat(proof.membershipAuthorityGeneration()).isEqualTo(1L); - assertThat(proof.eventSequence()).isEqualTo(1L); - var member = - members.findFreshMembershipForUpdate(login.accountId(), sources.tenant).orElseThrow(); - assertThat(member.getId()).isEqualTo(proof.membershipId()); - assertThat(member.getAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); - var pair = pairs.readForUpdate(login.accountId(), sources.tenant).orElseThrow(); - assertThat(pair.membershipExists()).isTrue(); - assertThat(pair.membershipVersion()).isEqualTo(proof.membershipVersion()); - assertThat(pair.membershipAuthorityGeneration()) - .isEqualTo(proof.membershipAuthorityGeneration()); - assertThat(pair.eventSequence()).isEqualTo(proof.eventSequence()); - assertThat(pair.eventId()).isEqualTo(proof.eventId()); - assertThat(pair.eventDigest()).isEqualTo(proof.eventDigest()); - assertThat(pair.lastTransitionInvalidated()).isFalse(); - var checkpoint = outbox.readCheckpoint(proof.eventStreamKey()).orElseThrow(); - assertThat(checkpoint.outboxSequence()).isEqualTo(proof.eventSequence()); - assertThat(checkpoint.sourceEventId()).isEqualTo(proof.eventId()); - assertThat(checkpoint.sourceEventDigest()).isEqualTo(proof.eventDigest()); - var event = outbox.findEvent(proof.eventStreamKey(), proof.eventSequence()).orElseThrow(); - assertThat(event.requestId()).isEqualTo(requestId); - assertThat(event.eventId()).isEqualTo(proof.eventId()); - assertThat(event.eventDigest()).isEqualTo(proof.eventDigest()); - var decoded = - MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); - assertThat(event.payload()).containsExactly(decoded.canonicalJsonUtf8()); - var audit = audits.findCanonicalTenantEnvelopeForUpdate(proof.auditEventId()).orElseThrow(); - assertThat(audit.tenantUuid()).isEqualTo(sources.tenant); - assertThat(audit.tenantIdentityVersion()).isEqualTo(2); - assertThat(audit.eventType()).isEqualTo("ACCOUNT_JOINED_PUBLIC_PRODUCTION"); - assertThat(audit.producerService()).isEqualTo("account-service"); - assertThat(audit.payloadDigest()).isEqualTo(proof.auditPayloadDigest()); - assertThat(audit.occurredAt()).isEqualTo(proof.auditOccurredAt()); - assertAdmittingSnapshot(snapshots.readCurrent(login.accountId(), sources.tenant)); - } - - private void assertAdmittingSnapshot(Snapshot current) { - assertThat(current.accountId()).isEqualTo(login.accountId().toString()); - assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); - assertThat(current.membershipExists()).isTrue(); - assertThat(current.membershipLifecycleState()).isEqualTo("ACTIVE"); - assertThat(current.gameplayAdmissionAllowed()).isTrue(); - assertThat(current.roles()).containsExactly("player"); - assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "2"); - assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); - } - - private T transactional(T target, Class type) { - var proxy = new ProxyFactory(target); - proxy.setProxyTargetClass(true); - proxy.addAdvice( - new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); - return type.cast(proxy.getProxy(type.getClassLoader())); - } - - /** Exact current source comparison after the receiving client has authenticated the response. */ - public void assertNonAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence evidence) { - Objects.requireNonNull(evidence, "Actual Account receiver evidence is required"); - evidence.requireCurrentAt(clock.instant()); - var current = sources.tx(() -> snapshots.readCurrent(login.accountId(), sources.tenant)); - assertThat(evidence.membershipSource()).isEqualTo(current); - assertAbsentMembership(); - } - - /** Confirms actual absence enrollment and current tenant DEMO source without editing history. */ - public void assertAbsentMembership() { - sources.tx( - () -> { - var current = snapshots.readCurrent(login.accountId(), sources.tenant); - assertThat(current.accountId()).isEqualTo(login.accountId().toString()); - assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); - assertThat(current.membershipExists()).isFalse(); - assertThat(current.membershipLifecycleState()).isEqualTo("MISSING"); - assertThat(current.gameplayAdmissionAllowed()).isFalse(); - assertThat(current.roles()).isEmpty(); - assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "1"); - assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); - assertThat(demos.revalidate(demo)).isEqualTo(demo); - return null; - }); - login.assertCreatorRemainsNonAdmitting(); - verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); - } - - private static void requireFirstDemoRequest( - DemoTenantEntitlementRequest request, FreshTenantCreationEvidence creation) { - Objects.requireNonNull(request, "Explicit controlled demo policy is required"); - if (!creation.canonicalTenantId().equals(request.canonicalTenantId()) - || !creation.creationRequestId().equals(request.tenantCreationRequestId()) - || !creation.requestDigest().equals(request.tenantCreationRequestDigest()) - || request.expectedEntitlementVersion() != null - || request.expectedTenantAuthorityGeneration() != null - || request.expectedTenantAuthoritySourceVersion() != null) { - throw new IllegalArgumentException( - "First DEMO request must preserve exact creation provenance"); - } - } - - private static String scopeSigningKey() { - byte[] bytes = new byte[32]; - RANDOM.nextBytes(bytes); - try { - return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); - } finally { - Arrays.fill(bytes, (byte) 0); - } - } - - private static T excluded(Class type) { - return mock( - type, - invocation -> { - throw new AssertionError( - "Excluded paid/browser dependency invoked: " + type.getSimpleName()); - }); - } -} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java deleted file mode 100644 index ad28fb69a8..0000000000 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java +++ /dev/null @@ -1,523 +0,0 @@ -package net.firedevops.firemud.accountservice.service.session; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.SecureRandom; -import java.time.Clock; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; -import javax.crypto.spec.SecretKeySpec; -import net.firedevops.firemud.account.v1.AuthenticateRequest; -import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; -import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; -import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; -import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; -import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution; -import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; -import org.springframework.transaction.interceptor.TransactionInterceptor; -import tools.jackson.databind.json.JsonMapper; - -/** - * Shared-source Account LOGIN composition for the original creator or a separate global player. SQL - * owners, primary verification, signer correspondence, encrypted response recovery, and physical - * Redis registration/projection are real; upstream creator/legal/platform evidence, key custody, - * the newly stored OTP, and the verified caller argument remain controlled inputs. - * - *

This helper borrows the original fixture's connections and does not activate runtime wiring. - * Its ACTIVE tenantAdmin creator membership remains non-admitting. LOGIN establishes global - * identity only; no positive membership, entitlement, connect scope, or PLAY authority is made. - */ -public final class AccountPlayerAdmissionSharedOwnerFixture { - private static final SecureRandom RANDOM = new SecureRandom(); - private static final int REGISTRY_BYTES = - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; - private static final long REGISTRY_CLEANUP_MILLIS = 30_000L; - private final AccountControlUiOwnerSourcesFixture sources; - private final Account account; - private final AccountJwtJwksTrustedSource publicSource; - private final Clock clock; - private final AccountCoordinationPinnedConnectionProvider connections; - private final AccountGameplayDelegationIssuanceRepository issuance; - private final AccountAuthoritySourceEvidenceRepository authoritySources; - private final AccountGameplayDelegationAuthorityProjection projection; - private final AccountGameplayCanonicalLoginOwner login; - private final AccountGameplayPrimaryCredentialVerifier verifier; - private final AccountGameplayDelegationCommittedIssuanceOwner committedOwner; - private final AccountInitialGameplayLoginDisposalOwner disposal; - private final List ownerObservations = new CopyOnWriteArrayList<>(); - private final String otp = "shared-login-" + UUID.randomUUID(); - - public AccountPlayerAdmissionSharedOwnerFixture( - AccountControlUiOriginalOrderFixture original, Path temporary) throws Exception { - this(original, temporary, Clock.systemUTC()); - } - - public AccountPlayerAdmissionSharedOwnerFixture( - AccountControlUiOriginalOrderFixture original, Path temporary, Clock clock) throws Exception { - this(original, temporary, clock, false); - } - - static AccountPlayerAdmissionSharedOwnerFixture freshGlobalPlayer( - AccountControlUiOriginalOrderFixture original, Path temporary, Clock clock) throws Exception { - return new AccountPlayerAdmissionSharedOwnerFixture(original, temporary, clock, true); - } - - private AccountPlayerAdmissionSharedOwnerFixture( - AccountControlUiOriginalOrderFixture original, - Path temporary, - Clock clock, - boolean separateGlobalPlayer) - throws Exception { - Objects.requireNonNull(original, "Original Account owner fixture is required"); - this.clock = Objects.requireNonNull(clock, "Clock is required"); - sources = original.preparedOriginalCreator().sources(); - account = - separateGlobalPlayer - ? sources.createGlobalAccount("shared-player-" + UUID.randomUUID()) - : sources.account; - publicSource = original.publicSource; - connections = original.gameplayConnectionProvider(); - assertCreatorRemainsNonAdmitting(); - assertThat(sources.challenges.findByAccountId(account.getId())).isEmpty(); - - var generations = new AccountAuthorityGenerationRepository(sources.dsl); - var outbox = new AccountAuthorityOutboxRepository(sources.dsl); - authoritySources = - new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); - sources.tx( - () -> { - authoritySources.initializeIssuerIfAbsent(GameSessionAccountDelegationProfile.ISSUER); - return null; - }); - var bundles = new AccountAuthEvidenceBundleRepository(sources.dsl, generations, outbox); - var issuanceTarget = - new AccountGameplayDelegationIssuanceRepository(sources.dsl, authoritySources, bundles); - // Preserve MANDATORY writes and independent REQUIRES_NEW committed-proof readbacks. - var issuanceProxy = new ProxyFactory(issuanceTarget); - issuanceProxy.setProxyTargetClass(true); - issuanceProxy.addAdvice( - new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); - issuance = - observed( - AccountGameplayDelegationIssuanceRepository.class, - (AccountGameplayDelegationIssuanceRepository) - issuanceProxy.getProxy( - AccountGameplayDelegationIssuanceRepository.class.getClassLoader())); - var cryptography = - new AccountResponseEnvelopeCryptography( - new AccountResponseEnvelopeKeyring(writeResponseKeyring(temporary).toString())); - var envelopes = - new AccountGameplayDelegationResponseEnvelopeRepository( - sources.dsl, authoritySources, bundles, issuance, cryptography); - var lifecycle = original.signerFixture; - var signer = - observed( - AccountGameplayDelegationSigner.class, - new AccountGameplayDelegationSigner( - issuance, - lifecycle.desired, - lifecycle.trust, - lifecycle.api, - original.publicSource, - new AccountGameplayDelegationResponseEnvelopeService(envelopes), - sources.manager, - clock, - lifecycle.privateRoot, - Path.of("current.key"), - lifecycle.publicRoot, - Path.of("jwks.json"))); - var redis = - observed( - AccountGameplayDelegationRedisClient.class, - new AccountGameplayDelegationRedisClient( - connections, - loginScriptCatalog(), - new AcknowledgementRequirements(1, 1, 5_000), - clock, - REGISTRY_BYTES, - AccountPlayerAdmissionSharedOwnerFixture.class.getClassLoader())); - projection = - observed( - AccountGameplayDelegationAuthorityProjection.class, - new AccountGameplayDelegationAuthorityProjection( - authoritySources, sources.manager, redis)); - var registry = - observed( - AccountGameplayDelegationTokenRegistry.class, - new AccountGameplayDelegationTokenRegistry( - issuance, sources.manager, redis, clock, REGISTRY_BYTES, REGISTRY_CLEANUP_MILLIS)); - disposal = - observed( - AccountInitialGameplayLoginDisposalOwner.class, - new AccountInitialGameplayLoginDisposalOwner( - observed( - AccountInitialGameplayLoginDisposalRepository.class, - new AccountInitialGameplayLoginDisposalRepository(sources.dsl)), - registry, - sources.manager)); - var commit = - observed( - AccountGameplayDelegationIssuanceCommitService.class, - new AccountGameplayDelegationIssuanceCommitService( - signer, registry, projection, issuance, sources.manager, clock)); - committedOwner = - observed( - AccountGameplayDelegationCommittedIssuanceOwner.class, - new AccountGameplayDelegationCommittedIssuanceOwner( - issuance, signer, registry, sources.manager, clock)); - var recovery = - observed( - AccountGameplayDelegationResponseRecoveryOwner.class, - new AccountGameplayDelegationResponseRecoveryOwner( - envelopes, committedOwner, sources.manager)); - verifier = - observed( - AccountGameplayPrimaryCredentialVerifier.class, - new AccountGameplayPrimaryCredentialVerifier(sources.primary)); - login = - observed( - AccountGameplayCanonicalLoginOwner.class, - new AccountGameplayCanonicalLoginOwner( - sources.accounts, - issuance, - digestKeys(clock), - commit, - recovery, - sources.manager, - clock)); - // Control-UI consumed the original challenge. Never resurrect or reuse that consumed row. - sources.installGlobalOtp(account, otp); - } - - /** Bounded stage names only; no invocation arguments, results, SQL or token material. */ - public List ownerObservations() { - return List.copyOf(ownerObservations); - } - - private T observed(Class type, T actual) { - return org.mockito.Mockito.mock( - type, - invocation -> { - String operation = type.getSimpleName() + "." + invocation.getMethod().getName(); - ownerObservations.add(operation + ":ENTER"); - try { - Object result = invocation.getMethod().invoke(actual, invocation.getArguments()); - ownerObservations.add(operation + ":OK"); - return result; - } catch (InvocationTargetException wrapped) { - Throwable failure = wrapped.getCause(); - String sqlState = - failure instanceof org.jooq.exception.DataAccessException sql - ? sql.sqlState() - : "none"; - ownerObservations.add( - operation + ":" + failure.getClass().getSimpleName() + ":" + sqlState); - throw failure; - } - }); - } - - public UUID accountId() { - return account.getAccountUuid(); - } - - public FreshTenantCreationEvidence creationEvidence() { - return sources.creationEvidence; - } - - /** The test supplies caller coordinates; the actual owner binds and consumes the fresh OTP. */ - public CanonicalGameplayLoginRequest loginRequest( - UUID requestId, GameplayCredentialSourceContext context) { - return new CanonicalGameplayLoginRequest(requestId, account.getEmail(), otp, context); - } - - /** - * Real stored OTP input for the canonical receiver; source/socket custody is caller-controlled. - */ - public AuthenticateRequest wireLoginRequest( - UUID requestId, GameplayCredentialSourceContext context) { - var request = loginRequest(requestId, context); - if (!"trusted_tcp_proxy".equals(context.transportClass())) { - throw new IllegalArgumentException("Canonical receiver requires trusted TCP Proxy context"); - } - return AuthenticateRequest.newBuilder() - .setRequestId(request.requestId().toString()) - .setEmail(account.getEmail()) - .setPassword(otp) - .setSourceContext( - GameplayLoginSourceContext.newBuilder() - .setCallerContextId(context.contextId().toString()) - .setCanonicalClientAddress(context.canonicalClientAddress()) - .setTransportClass( - GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) - .build(); - } - - /** - * The caller must install the real TLS peer interceptor on its private mTLS server. Known-token - * retirement uses the same SQL/Redis owners; unqualified no-binding disposal remains PENDING. - */ - public AccountGameplayAuthenticateReceiver authenticateReceiver(String namespace) { - if (!creationEvidence().targetNamespace().equals(namespace)) { - throw new IllegalArgumentException("Receiver namespace must match the shared tenant source"); - } - return new AccountGameplayAuthenticateReceiver(login, verifier, namespace, disposal); - } - - /** Actual receipt-backed public source, not a replacement JWKS document. */ - public AccountJwtJwksTrustedSource trustedJwksSource() { - return publicSource; - } - - AccountGameplayAdmissionCallerVerifier admissionCallerVerifier() { - return new AccountGameplayAdmissionCallerVerifier(publicSource, committedOwner, clock); - } - - AccountGameplayDelegationIssuanceRepository issuanceRepository() { - return issuance; - } - - /** Direct owner invocation, not evidence of an authenticated transport or deployed caller. */ - public InitialGameplayLoginResult authenticate( - CanonicalGameplayLoginRequest request, String verifiedGameSessionWorkload) { - return login.authenticate(request, verifiedGameSessionWorkload, verifier); - } - - /** Exact SQL, active Redis, and projection readback; identity remains distinct from admission. */ - public void assertCommittedNonAdmittingLogin(InitialGameplayLoginResult result) { - assertThat(result.accountId()).isEqualTo(accountId()); - assertThat(result.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); - assertCommittedNonAdmittingLogin( - result.requestId(), - result.callerContextId(), - result.tokenJti(), - result.tokenSha256(), - result.expiresAtEpochSecond()); - } - - /** Compares nonsecret receiving-client evidence to actual SQL, Redis and current sources. */ - public void assertCommittedNonAdmittingLogin( - UUID requestId, - UUID callerContextId, - UUID tokenJti, - String tokenSha256, - long expiresAtEpochSecond) { - assertThat(sources.challenges.findByAccountId(account.getId())).isEmpty(); - var replay = sources.tx(() -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); - assertThat(replay.state()).isEqualTo(GameplayLoginReplayState.COMMITTED); - var committed = sources.tx(() -> issuance.readCurrentCommittedCandidate(requestId)); - assertThat(committed.identity()).isEqualTo(replay.identity()); - assertThat(committed.identity().accountId()).isEqualTo(accountId()); - assertThat(committed.identity().callerContextId()).isEqualTo(callerContextId); - assertThat(committed.identity().tokenJti()).isEqualTo(tokenJti); - assertThat(committed.tokenSha256()).isEqualTo(tokenSha256); - assertThat(committed.commitProofSha256()).isNotBlank(); - assertThat(committed.registrationLocalAofCount()).isGreaterThanOrEqualTo(1L); - assertThat(committed.registrationReplicaAofCount()).isGreaterThanOrEqualTo(1L); - assertThat(committed.registryAbsoluteExpiryMillis()) - .isEqualTo( - Math.addExact( - Math.multiplyExact(expiresAtEpochSecond, 1_000L), REGISTRY_CLEANUP_MILLIS)); - var snapshot = - sources.tx( - () -> - authoritySources.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, accountId())); - byte[][] expected = - AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot); - var observation = projection.observeCurrent(accountId()); - assertThat(observation.issuerGeneration()).isEqualTo(snapshot.issuer().generation()); - assertThat(observation.accountGeneration()).isEqualTo(snapshot.account().generation()); - try (var connection = connections.openPinnedConnection()) { - var commands = connection.sync(); - assertThat(commands.aclWhoami()) - .isEqualTo(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); - byte[] tokenKey = ascii(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + tokenSha256); - var active = - GameSessionAccountDelegationRegistryRecord.decode(commands.get(tokenKey), REGISTRY_BYTES); - assertThat(active.state()).isEqualTo("active"); - assertThat(active.tokenHash()).isEqualTo(tokenSha256); - assertThat(active.requestId()).isEqualTo(requestId.toString()); - assertThat(commands.pexpiretime(tokenKey)) - .isEqualTo(committed.registryAbsoluteExpiryMillis()); - assertThat( - commands.get( - ascii( - AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX - + GameSessionAccountDelegationProfile.ISSUER))) - .containsExactly(expected[0]); - assertThat( - commands.get( - ascii( - AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX - + accountId()))) - .containsExactly(expected[1]); - } - assertCreatorRemainsNonAdmitting(); - if (!accountId().equals(sources.account.getAccountUuid())) { - sources.tx( - () -> { - var fresh = - new FreshTenantIdentityAssociationRepository( - sources.dsl, creationEvidence().targetNamespace()); - var memberships = - new AccountTenantMembershipRepository( - sources.dsl, - sources.accounts, - fresh, - new AccountMembershipPairAuthorityRepository(sources.dsl)); - assertThat(memberships.findFreshMembership(accountId(), sources.tenant)).isEmpty(); - return null; - }); - } - } - - /** Real canonical membership and role readback, with the original source tuple unchanged. */ - public void assertCreatorRemainsNonAdmitting() { - UUID creatorId = sources.account.getAccountUuid(); - sources.tx( - () -> { - var fresh = - new FreshTenantIdentityAssociationRepository( - sources.dsl, creationEvidence().targetNamespace()); - assertThat(fresh.read(sources.tenant)).contains(creationEvidence()); - var pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); - var memberships = - new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); - var membership = memberships.findFreshMembership(creatorId, sources.tenant).orElseThrow(); - assertThat(membership.getLifecycleState()).isEqualTo("ACTIVE"); - assertThat(membership.getAuthorityProvenance()).isEqualTo("TENANT_CREATION"); - assertThat(membership.isGameplayAdmissionAllowed()).isFalse(); - var pair = pairs.readPositive(creatorId, sources.tenant).orElseThrow(); - var roles = - new AccountTenantMembershipRoleSnapshotRepository(sources.dsl) - .findForCanonicalUpdate( - creatorId, - sources.tenant, - pair.provenance(), - membership.getId(), - membership.getMembershipVersion()) - .orElseThrow(); - assertThat(roles.roles()).containsExactly("tenantAdmin"); - return null; - }); - } - - private static Path writeResponseKeyring(Path temporary) throws IOException { - Path root = - Files.createTempDirectory(Files.createDirectories(temporary), "shared-login-keyring-") - .toAbsolutePath(); - byte[] key = new byte[32]; - RANDOM.nextBytes(key); - try { - Files.writeString( - root.resolve("keyring"), - "firemud-account-response-envelope-keyring-v1\nactive shared-login " - + Base64.getUrlEncoder().withoutPadding().encodeToString(key) - + "\n", - StandardCharsets.US_ASCII); - } finally { - Arrays.fill(key, (byte) 0); - } - return root; - } - - private static AccountGameplayCredentialRequestDigestKeySource digestKeys(Clock clock) { - byte[] key = new byte[32]; - RANDOM.nextBytes(key); - CredentialDigestKey digest; - try { - digest = - new CredentialDigestKey( - "shared-login", - new SecretKeySpec(key, "HmacSHA256"), - Instant.now(clock).plusSeconds(3_600)); - } finally { - Arrays.fill(key, (byte) 0); - } - return new AccountGameplayCredentialRequestDigestKeySource() { - @Override - public CredentialDigestKey currentKey() { - return digest; - } - - @Override - public CredentialDigestKey requireKey(String keyId) { - if (!digest.keyId().equals(keyId)) { - throw new IllegalStateException("Unknown test-only LOGIN digest key"); - } - return digest; - } - }; - } - - private static RedisScriptCatalog loginScriptCatalog() throws IOException { - List descriptors = new ArrayList<>(); - var json = JsonMapper.builder().build(); - for (String resource : - List.of( - "/redis/scripts/account-game-session-delegation-pending-register.json", - "/redis/scripts/account-game-session-delegation-activate-committed.json", - "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", - "/redis/scripts/account-initial-gameplay-login-dispose.json")) { - try (var input = - AccountPlayerAdmissionSharedOwnerFixture.class.getResourceAsStream(resource)) { - if (input == null) throw new IllegalStateException("Account LOGIN descriptor is absent"); - descriptors.add(json.readValue(input, RedisScriptDescriptor.class)); - } - } - return RedisScriptCatalog.fromContributions( - List.of( - new AccountGenerationProjectionRedisScriptContribution(), - new RedisScriptContribution() { - @Override - public String ownerId() { - return "account-service"; - } - - @Override - public Collection descriptors() { - return List.copyOf(descriptors); - } - })); - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.US_ASCII); - } -} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java deleted file mode 100644 index ced10986f5..0000000000 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java +++ /dev/null @@ -1,588 +0,0 @@ -package net.firedevops.firemud.common.account.authority; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.LinkedHashMap; -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.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import tools.jackson.core.StreamReadConstraints; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.core.json.JsonFactory; -import tools.jackson.core.type.TypeReference; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; - -/** - * Account's PUBLIC_PRODUCTION SHARED PRESEEDED PLAYER_ADMISSION variant of the existing runtime - * evidence contract. Content validation is not source authentication or an admission grant. - * - *

The owner must derive this value from its final Account transaction and protected target read. - * Target source references name that complete read; they hold no World lock through later use. - * Decoding validates content only and cannot promote caller-supplied data to source authority. - */ -public final class RuntimePlayerAdmissionEntitlementEvidence { - public static final String SCHEMA = RuntimeTenantOperationEntitlementEvidence.SCHEMA; - public static final String VARIANT = "PLAYER_ADMISSION"; - public static final int MAX_CANONICAL_BYTES = 256 * 1024; - public static final int MAX_CONNECT_SCOPE_CHARS = 16384; - private static final JsonMapper JSON = - JsonMapper.builder( - JsonFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - .maxNestingDepth(16) - .maxStringLength(65536) - .maxNumberLength(19) - .build()) - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .build()) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); - private static final Set TARGET_FIELDS = - Set.of( - "targetClass", - "characterCreationPolicy", - "targetNamespace", - "tenantId", - "tenantSlug", - "worldSlug", - "realmId", - "realmSlug", - "playableStateNamespaceId", - "playableStateScope", - "gameInstanceId", - "canonicalVersionId", - "catalogRevision", - "pointerVersion", - "activeWorldEpoch", - "evaluatedAt", - "connectScopeExpiresAt"); - private static final Set FACT_FIELDS = - Set.of( - "sourceKind", - "subscriptionStatus", - "provisioningStatus", - "gameplayAvailable", - "allowPublicJoin", - "allowNewGameplayBindings", - "allowNewInstanceStarts", - "quotas", - "entitlementVersion", - "tenantBillingSequence", - "tenantAuthorityGeneration"); - private static final Set SOURCE_FIELDS = - Set.of( - "callerTokenJti", - "callerTokenExpiresAt", - "paidReceiptValidUntil", - "callerTokenSha256", - "callerRegistryRecordSha256", - "callerCommitProofSha256", - "callerContextId", - "callerOperationId", - "scopeDigest", - "entitlementSourceDigest", - "admissionPointerSnapshotDigest", - "gameSessionOwnerProofDigest", - "publishedPolicySetDigest", - "worldLifecycleDigest", - "worldCaptureId", - "worldRowVersion"); - private final Snapshot membership; - private final byte[] canonicalBytes; - - private RuntimePlayerAdmissionEntitlementEvidence(Snapshot membership, byte[] canonicalBytes) { - this.membership = membership; - this.canonicalBytes = canonicalBytes.clone(); - } - - /** Content-only construction; production source provenance belongs to the Account owner. */ - public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( - UUID requestId, - String callerWorkload, - String verifiedConnectScopeId, - Snapshot membership, - Map target, - Map facts, - Map source, - Instant evaluatedAt) { - Objects.requireNonNull(membership); - RuntimeMembershipAuthorityEvidenceValidator.validate(membership); - requireUuid(membership.accountId()); - requireUuid(membership.tenantId()); - if (!membership.authorityTuple().privateRealmGrantVersions().isEmpty()) - throw invalid("Public player evidence cannot carry private grant authority"); - if (!"firemud-account-service".equals(membership.issuerId())) - throw invalid("Canonical Account issuer required"); - requireUuid(requestId.toString()); - var peer = - GrpcPeerIdentity.parseUri(callerWorkload) - .filter( - value -> - value.uri().equals(callerWorkload) - && "game-session-service".equals(value.service())) - .orElseThrow(() -> invalid("Exact Game Session caller required")); - if (verifiedConnectScopeId == null - || verifiedConnectScopeId.isBlank() - || verifiedConnectScopeId.length() > MAX_CONNECT_SCOPE_CHARS) - throw invalid("Verified connect scope required"); - exact(target, TARGET_FIELDS); - exact(facts, FACT_FIELDS); - exact(source, SOURCE_FIELDS); - if (!"PUBLIC_PRODUCTION".equals(target.get("targetClass")) - || !"PRESEEDED_ONLY".equals(target.get("characterCreationPolicy")) - || !peer.namespace().equals(target.get("targetNamespace")) - || !membership.tenantId().equals(target.get("tenantId")) - || !"SHARED".equals(target.get("playableStateScope"))) - throw invalid("Exact public SHARED tenant target required"); - for (String key : - List.of( - "tenantId", - "realmId", - "playableStateNamespaceId", - "gameInstanceId", - "canonicalVersionId")) requireUuid(text(target.get(key))); - for (String key : List.of("tenantSlug", "worldSlug", "realmSlug")) - if (!text(target.get(key)).matches("[a-z0-9]+(?:-[a-z0-9]+)*")) - throw invalid("Canonical slug required"); - for (String key : List.of("catalogRevision", "pointerVersion", "activeWorldEpoch")) - positive(target.get(key)); - Instant scopeTime = instant(target.get("evaluatedAt")); - Instant scopeExpiry = instant(target.get("connectScopeExpiresAt")); - if (!evaluatedAt.isAfter(Instant.EPOCH) - || evaluatedAt.isBefore(scopeTime) - || !evaluatedAt.isBefore(scopeExpiry)) throw invalid("Scope is not current at evaluation"); - validateFacts(facts, membership); - for (String key : - List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) - requireUuid(text(source.get(key))); - for (String key : - List.of("callerTokenSha256", "callerRegistryRecordSha256", "callerCommitProofSha256")) - if (!text(source.get(key)).matches("[0-9a-f]{64}")) throw invalid("Source SHA-256 required"); - for (String key : - List.of( - "scopeDigest", - "entitlementSourceDigest", - "worldLifecycleDigest", - "publishedPolicySetDigest", - "gameSessionOwnerProofDigest")) - if (!text(source.get(key)).matches("sha256:[0-9a-f]{64}")) - throw invalid("Source digest required"); - for (String key : List.of("admissionPointerSnapshotDigest")) - if (!text(source.get(key)).matches("[0-9a-f]{64}")) - throw invalid("Canonical target source digest required"); - if (!text(source.get("worldRowVersion")).matches("0|[1-9][0-9]{0,18}") - || Long.parseLong(text(source.get("worldRowVersion"))) < 0) - throw invalid("World row version required"); - Instant validUntil = instant(source.get("callerTokenExpiresAt")); - if (scopeExpiry.isBefore(validUntil)) validUntil = scopeExpiry; - if ("PAID_HOSTING".equals(facts.get("sourceKind"))) { - Instant providerDeadline = instant(source.get("paidReceiptValidUntil")); - if (providerDeadline.isBefore(validUntil)) validUntil = providerDeadline; - } else if (source.get("paidReceiptValidUntil") != null) { - throw invalid("Demo evidence cannot assert a paid receipt deadline"); - } - if (!evaluatedAt.isBefore(validUntil)) throw invalid("Player source validity expired"); - Map fields = new LinkedHashMap<>(); - fields.put("schema", SCHEMA); - fields.put("variant", VARIANT); - fields.put("bundleVersion", "1"); - fields.put("authorityAvailability", "AVAILABLE"); - fields.put("issuer", membership.issuerId()); - fields.put("tenantId", membership.tenantId()); - fields.put("callerAccountId", membership.accountId()); - fields.put("callerWorkload", callerWorkload); - fields.put("verifiedConnectScopeId", verifiedConnectScopeId); - fields.put("target", target); - fields.putAll(facts); - fields.put("membershipExists", membership.membershipExists()); - fields.put("membershipLifecycleState", membership.membershipLifecycleState()); - fields.put("gameplayAdmissionAllowed", membership.gameplayAdmissionAllowed()); - fields.put("membershipVersion", membership.membershipVersion()); - fields.put("membershipAuthorityGeneration", membership.membershipAuthorityGeneration()); - fields.put("roles", membership.roles()); - fields.put("issuanceFence", membership.issuanceFence()); - fields.put("authorityTuple", tuple(membership)); - fields.put( - "outboxCheckpoints", - membership.checkpoints().stream() - .map( - checkpoint -> { - Map entry = new LinkedHashMap<>(); - entry.put("outboxStreamKey", checkpoint.outboxStreamKey()); - entry.put("outboxSequence", checkpoint.outboxSequence()); - membership.sourceEvidence().stream() - .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) - .findFirst() - .ifPresent( - event -> { - entry.put("sourceEventId", event.eventId()); - entry.put("sourceEventDigest", event.eventDigest()); - }); - return entry; - }) - .toList()); - fields.put("authoritySourceEvidence", membership.sourceEvidence()); - fields.put("sourceReferences", source); - fields.put("validUntil", validUntil.toString()); - // The committed-input identity excludes the request and evaluation time. Source references - // include the actual caller issuance, retained scope, billing and protected target captures. - String snapshotIdentity = digest(fields); - fields.put("snapshotIdentity", snapshotIdentity); - fields.put("requestId", requestId.toString()); - fields.put("evaluatedAt", evaluatedAt.toString()); - fields.put( - "evaluationIdentity", - digest( - Map.of( - "snapshotIdentity", - snapshotIdentity, - "requestId", - requestId.toString(), - "callerWorkload", - callerWorkload, - "evaluatedAt", - evaluatedAt.toString()))); - byte[] bytes = canonical(fields); - if (bytes.length > MAX_CANONICAL_BYTES) throw invalid("Player evidence exceeds size bound"); - return new RuntimePlayerAdmissionEntitlementEvidence(membership, bytes); - } - - /** Strict content decoder only; authenticated transport and Account sources remain mandatory. */ - public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] bytes) { - if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) - throw invalid("Player evidence is absent or exceeds size bound"); - try { - String json = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - Map fields = JSON.readValue(json, new TypeReference<>() {}); - Map authority = object(fields.get("authorityTuple")); - Set requiredTuple = - Set.of( - "issuerAuthGeneration", - "accountAuthorityGeneration", - "tenantAuthorityGeneration", - "membershipAuthorityGeneration", - "privateRealmGrantVersions"); - if (!authority.keySet().containsAll(requiredTuple) - || authority.keySet().stream() - .anyMatch( - k -> - !requiredTuple.contains(k) - && !Set.of("accountSecurityCutoff", "tenantBillingCutoff").contains(k)) - || !list(authority.get("privateRealmGrantVersions")).isEmpty()) - throw invalid("Closed public authority tuple required"); - Optional accountCutoff = - Optional.empty(); - if (authority.containsKey("accountSecurityCutoff")) { - var cutoff = object(authority.get("accountSecurityCutoff")); - exact(cutoff, Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence")); - accountCutoff = - Optional.of( - new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( - text(cutoff.get("accountAuthorityGeneration")), - text(cutoff.get("outboxStreamKey")), - text(cutoff.get("outboxSequence")))); - } - Map tenantCutoffs = - new LinkedHashMap<>(); - object(authority.get("tenantBillingCutoff")) - .forEach( - (tenant, raw) -> { - var cutoff = object(raw); - exact( - cutoff, - Set.of( - "tenantAuthorityGeneration", - "tenantBillingSequence", - "outboxStreamKey", - "outboxSequence")); - tenantCutoffs.put( - tenant, - new MembershipAuthorityEventV1Codec.TenantBillingCutoff( - text(cutoff.get("tenantAuthorityGeneration")), - text(cutoff.get("tenantBillingSequence")), - text(cutoff.get("outboxStreamKey")), text(cutoff.get("outboxSequence")))); - }); - var tuple = - new MembershipAuthorityEventV1Codec.AuthorityTuple( - text(authority.get("issuerAuthGeneration")), - text(authority.get("accountAuthorityGeneration")), - strings(authority.get("tenantAuthorityGeneration")), - strings(authority.get("membershipAuthorityGeneration")), - List.of(), - accountCutoff, - Optional.of(tenantCutoffs)); - var checkpoints = - list(fields.get("outboxCheckpoints")).stream() - .map( - raw -> { - var checkpoint = object(raw); - String stream = text(checkpoint.get("outboxStreamKey")); - String sequence = text(checkpoint.get("outboxSequence")); - return new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( - stream, sequence); - }) - .toList(); - var events = - list(fields.get("authoritySourceEvidence")).stream() - .map( - raw -> { - var event = object(raw); - exact( - event, - Set.of( - "outboxStreamKey", - "outboxSequence", - "eventId", - "eventDigest", - "canonicalEventJson")); - return new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( - text(event.get("outboxStreamKey")), - text(event.get("outboxSequence")), - text(event.get("eventId")), - text(event.get("eventDigest")), - text(event.get("canonicalEventJson"))); - }) - .toList(); - Snapshot membership = - new Snapshot( - text(fields.get("issuer")), - text(fields.get("callerAccountId")), - text(fields.get("tenantId")), - bool(fields.get("membershipExists")), - text(fields.get("membershipLifecycleState")), - bool(fields.get("gameplayAdmissionAllowed")), - strings(fields.get("membershipVersion")), - text(fields.get("membershipAuthorityGeneration")), - list(fields.get("roles")).stream() - .map(RuntimePlayerAdmissionEntitlementEvidence::text) - .toList(), - tuple, - text(fields.get("issuanceFence")), - checkpoints, - events); - Map facts = new LinkedHashMap<>(); - FACT_FIELDS.forEach(key -> facts.put(key, fields.get(key))); - var rebuilt = - fromOwnerEvaluation( - UUID.fromString(text(fields.get("requestId"))), - text(fields.get("callerWorkload")), - text(fields.get("verifiedConnectScopeId")), - membership, - object(fields.get("target")), - facts, - object(fields.get("sourceReferences")), - instant(fields.get("evaluatedAt"))); - if (!Arrays.equals(bytes, rebuilt.canonicalBytes)) - throw invalid("Player evidence must be the exact closed canonical value"); - return rebuilt; - } catch (CharacterCodingException failure) { - throw invalid("Player evidence requires strict UTF-8"); - } catch (RuntimeException failure) { - throw invalid("Invalid canonical player evidence"); - } - } - - private static Map object(Object value) { - if (!(value instanceof Map map)) throw invalid("Object required"); - Map result = new LinkedHashMap<>(); - map.forEach((key, member) -> result.put(text(key), member)); - return result; - } - - private static Map strings(Object value) { - Map result = new LinkedHashMap<>(); - object(value).forEach((key, member) -> result.put(key, text(member))); - return result; - } - - private static List list(Object value) { - if (!(value instanceof List list) || list.size() > 16) - throw invalid("Bounded list required"); - return list; - } - - private static boolean bool(Object value) { - if (!(value instanceof Boolean flag)) throw invalid("Boolean required"); - return flag; - } - - private static Instant instant(Object value) { - String text = text(value); - Instant instant = Instant.parse(text); - if (!instant.toString().equals(text)) throw invalid("Canonical timestamp required"); - return instant; - } - - private static void validateFacts(Map facts, Snapshot membership) { - String kind = text(facts.get("sourceKind")); - if (!Set.of("PAID_HOSTING", "NON_PAID_DEMO").contains(kind) - || facts.get("provisioningStatus") != null) - throw invalid("Current explicit source required"); - Object status = facts.get("subscriptionStatus"); - if ("NON_PAID_DEMO".equals(kind) - ? status != null - : !(status instanceof String) - || !Set.of("trialing", "active", "past_due", "grace", "suspended", "canceled") - .contains(status)) throw invalid("Source subscription status differs"); - for (String key : - List.of( - "gameplayAvailable", - "allowPublicJoin", - "allowNewGameplayBindings", - "allowNewInstanceStarts")) - if (!(facts.get(key) instanceof Boolean)) - throw invalid("Explicit entitlement booleans required"); - positive(facts.get("entitlementVersion")); - positive(facts.get("tenantBillingSequence")); - positive(facts.get("tenantAuthorityGeneration")); - var tuple = membership.authorityTuple(); - var cutoff = - tuple - .tenantBillingCutoff() - .orElseThrow(() -> invalid("Billing cutoff required")) - .get(membership.tenantId()); - if (!Objects.equals( - tuple.tenantAuthorityGeneration().get(membership.tenantId()), - facts.get("tenantAuthorityGeneration")) - || cutoff == null - || !Objects.equals(cutoff.tenantBillingSequence(), facts.get("tenantBillingSequence"))) - throw invalid("Facts differ from current tenant authority"); - if (!(facts.get("quotas") instanceof Map quotas) - || !quotas - .keySet() - .equals(Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"))) - throw invalid("Complete quotas required"); - quotas - .values() - .forEach( - value -> { - if (!text(value).matches("0|[1-9][0-9]{0,18}") || Long.parseLong(text(value)) < 0) - throw invalid("Nonnegative quota required"); - }); - } - - private static Map tuple(Snapshot membership) { - var supplied = membership.authorityTuple(); - Map result = new LinkedHashMap<>(); - result.put("issuerAuthGeneration", supplied.issuerAuthGeneration()); - result.put("accountAuthorityGeneration", supplied.accountAuthorityGeneration()); - result.put("tenantAuthorityGeneration", supplied.tenantAuthorityGeneration()); - result.put("membershipAuthorityGeneration", supplied.membershipAuthorityGeneration()); - result.put("privateRealmGrantVersions", supplied.privateRealmGrantVersions()); - supplied.accountSecurityCutoff().ifPresent(value -> result.put("accountSecurityCutoff", value)); - supplied.tenantBillingCutoff().ifPresent(value -> result.put("tenantBillingCutoff", value)); - return result; - } - - private static void exact(Map fields, Set expected) { - if (fields == null || !fields.keySet().equals(expected)) - throw invalid("Missing or extra scoped fields"); - } - - private static String text(Object value) { - if (!(value instanceof String text) || text.isBlank()) throw invalid("Required text absent"); - return text; - } - - private static void requireUuid(String value) { - if (!UUID.fromString(value).toString().equals(value) || new UUID(0, 0).toString().equals(value)) - throw invalid("Canonical UUID required"); - } - - private static void positive(Object value) { - if (!text(value).matches("[1-9][0-9]{0,18}") || Long.parseLong(text(value)) <= 0) - throw invalid("Positive owner counter required"); - } - - private static byte[] canonical(Map value) { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (IOException failure) { - throw invalid("Cannot encode canonical player evidence"); - } - } - - public static String digest(Map preimage) { - return digestBytes(canonical(preimage)); - } - - public static String digestBytes(byte[] bytes) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 unavailable", impossible); - } - } - - public Instant evaluatedAt() { - return instant(fields().get("evaluatedAt")); - } - - public Instant validUntil() { - return instant(fields().get("validUntil")); - } - - /** Applies actual source time bounds only; this never establishes a current World hold. */ - public void requireCurrentAt(Instant now) { - Objects.requireNonNull(now); - if (now.isBefore(evaluatedAt()) || !now.isBefore(validUntil())) - throw invalid("Player entitlement source observation expired"); - } - - public Snapshot membershipSource() { - return membership; - } - - public byte[] canonicalBytes() { - return canonicalBytes.clone(); - } - - /** A detached copy; editing it cannot alter this value. */ - public Map fields() { - return JSON.readValue( - new String(canonicalBytes, StandardCharsets.UTF_8), new TypeReference<>() {}); - } - - private static IllegalArgumentException invalid(String message) { - return new IllegalArgumentException(message); - } - - @Override - public boolean equals(Object other) { - return other instanceof RuntimePlayerAdmissionEntitlementEvidence value - && Arrays.equals(canonicalBytes, value.canonicalBytes); - } - - @Override - public int hashCode() { - return Arrays.hashCode(canonicalBytes); - } - - @Override - public String toString() { - return "RuntimePlayerAdmissionEntitlementEvidence[PLAYER_ADMISSION, redacted]"; - } -} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java deleted file mode 100644 index 32ca98404d..0000000000 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ /dev/null @@ -1,298 +0,0 @@ -package net.firedevops.firemud.common.account.authority; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import org.junit.jupiter.api.Test; - -/** Controlled content fixtures, not source authentication, transport or owner execution. */ -class RuntimePlayerAdmissionEntitlementEvidenceTest { - private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); - private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); - private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; - private static final String HASH = "a".repeat(64); - private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); - - @Test - void canonicalVariantRetainsExplicitAbsenceAndCompleteApplicableAuthority() { - var value = capture(target(), facts(), sources(), NOW); - assertThat(value.fields()) - .containsEntry("variant", "PLAYER_ADMISSION") - .containsEntry("authorityAvailability", "AVAILABLE") - .containsEntry("callerAccountId", ACCOUNT.toString()) - .containsEntry("verifiedConnectScopeId", "controlled-scope") - .containsEntry("membershipExists", false) - .containsEntry("membershipLifecycleState", "MISSING"); - assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); - assertThat(value.membershipSource().checkpoints()).hasSize(4); - assertThat(value.membershipSource().sourceEvidence()).hasSize(1); - byte[] copy = value.canonicalBytes(); - copy[0] = 0; - value.fields().put("callerAccountId", TENANT.toString()); - assertThat(value.fields()).containsEntry("callerAccountId", ACCOUNT.toString()); - assertThat(value.toString()).doesNotContain("controlled-scope"); - assertThatThrownBy( - () -> RuntimeTenantOperationEntitlementEvidence.parseCanonical(value.canonicalBytes())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void identitiesBindActualInputsAndSeparateSnapshotFromEvaluation() { - var first = capture(target(), facts(), sources(), NOW); - var later = capture(target(), facts(), sources(), NOW.plusSeconds(1)); - assertThat(first.fields().get("snapshotIdentity")) - .isEqualTo(later.fields().get("snapshotIdentity")); - assertThat(first.fields().get("evaluationIdentity")) - .isNotEqualTo(later.fields().get("evaluationIdentity")); - var changed = sources(); - changed.put("worldLifecycleDigest", "sha256:" + "b".repeat(64)); - assertThat(capture(target(), facts(), changed, NOW).fields().get("snapshotIdentity")) - .isNotEqualTo(first.fields().get("snapshotIdentity")); - } - - @Test - void incompleteOrConflictingTargetFactsAndSourcesNeverProduceAValue() { - for (String field : List.of("activeWorldEpoch", "canonicalVersionId", "targetClass")) { - var target = target(); - target.remove(field); - assertThatThrownBy(() -> capture(target, facts(), sources(), NOW)) - .isInstanceOf(IllegalArgumentException.class); - } - for (String field : List.of("tenantAuthorityGeneration", "tenantBillingSequence")) { - var facts = facts(); - facts.put(field, "9"); - assertThatThrownBy(() -> capture(target(), facts, sources(), NOW)) - .isInstanceOf(IllegalArgumentException.class); - } - var unframedScopeSource = sources(); - unframedScopeSource.put("scopeDigest", HASH); - assertThatThrownBy(() -> capture(target(), facts(), unframedScopeSource, NOW)) - .isInstanceOf(IllegalArgumentException.class); - var target = target(); - target.put("characterCreationPolicy", "PLAYER_CREATED"); - assertThatThrownBy(() -> capture(target, facts(), sources(), NOW)) - .isInstanceOf(IllegalArgumentException.class); - var source = sources(); - source.put("callerGeneration", "1"); - assertThatThrownBy(() -> capture(target(), facts(), source, NOW)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> capture(target(), facts(), sources(), NOW.plusSeconds(120))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void strictDecoderRoundTripsAndRejectsNoncanonicalUnknownOrConflictingContent() { - var value = capture(target(), facts(), sources(), NOW); - assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) - .isEqualTo(value); - String json = new String(value.canonicalBytes(), StandardCharsets.UTF_8); - for (byte[] malformed : - List.of( - (" " + json).getBytes(StandardCharsets.UTF_8), - json.replace("\"variant\":\"PLAYER_ADMISSION\"", "\"variant\":\"TENANT_OPERATION\"") - .getBytes(StandardCharsets.UTF_8), - (json.substring(0, json.length() - 1) + ",\"unknown\":true}") - .getBytes(StandardCharsets.UTF_8), - (json.substring(0, json.length() - 1) + ",\"variant\":\"PLAYER_ADMISSION\"}") - .getBytes(StandardCharsets.UTF_8), - json.replace("\"membershipExists\":false", "\"membershipExists\":true") - .getBytes(StandardCharsets.UTF_8), - json.replace("\"pointerVersion\":\"3\"", "\"pointerVersion\":\"4\"") - .getBytes(StandardCharsets.UTF_8), - new byte[] {(byte) 0xc3, (byte) 0x28}, - new byte[RuntimePlayerAdmissionEntitlementEvidence.MAX_CANONICAL_BYTES + 1])) { - assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(malformed)) - .isInstanceOf(IllegalArgumentException.class); - } - } - - @Test - void validityIsMinimumOfActualScopeCallerAndPaidReceiptBounds() { - var source = sources(); - var demo = capture(target(), facts(), source, NOW); - assertThat(demo.validUntil()).isEqualTo(NOW.plusSeconds(90)); - demo.requireCurrentAt(NOW.plusSeconds(89)); - assertThatThrownBy(() -> demo.requireCurrentAt(NOW.plusSeconds(90))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> demo.requireCurrentAt(NOW.minusSeconds(1))) - .isInstanceOf(IllegalArgumentException.class); - var paid = facts(); - paid.put("sourceKind", "PAID_HOSTING"); - paid.put("subscriptionStatus", "active"); - source.put("paidReceiptValidUntil", NOW.plusSeconds(4).toString()); - var value = capture(target(), paid, source, NOW); - assertThat(value.validUntil()).isEqualTo(NOW.plusSeconds(4)); - assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) - .isEqualTo(value); - source.put("paidReceiptValidUntil", NOW.toString()); - assertThatThrownBy(() -> capture(target(), paid, source, NOW)) - .isInstanceOf(IllegalArgumentException.class); - source.put("paidReceiptValidUntil", null); - assertThatThrownBy(() -> capture(target(), paid, source, NOW)) - .isInstanceOf(IllegalArgumentException.class); - } - - private static RuntimePlayerAdmissionEntitlementEvidence capture( - Map target, - Map facts, - Map source, - Instant at) { - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); - } - - private static Map target() { - Map target = new LinkedHashMap<>(); - target.put("targetClass", "PUBLIC_PRODUCTION"); - target.put("characterCreationPolicy", "PRESEEDED_ONLY"); - target.put("targetNamespace", "prod"); - target.put("tenantId", TENANT.toString()); - target.put("tenantSlug", "tenant"); - target.put("worldSlug", "world"); - target.put("realmId", REQUEST.toString()); - target.put("realmSlug", "production"); - target.put("playableStateNamespaceId", REQUEST.toString()); - target.put("playableStateScope", "SHARED"); - target.put("gameInstanceId", REQUEST.toString()); - target.put("canonicalVersionId", REQUEST.toString()); - target.put("catalogRevision", "7"); - target.put("pointerVersion", "3"); - target.put("activeWorldEpoch", "5"); - target.put("evaluatedAt", NOW.minusSeconds(20).toString()); - target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); - return target; - } - - private static Map facts() { - Map facts = new LinkedHashMap<>(); - facts.put("sourceKind", "NON_PAID_DEMO"); - facts.put("subscriptionStatus", null); - facts.put("provisioningStatus", null); - for (String flag : - List.of( - "gameplayAvailable", - "allowPublicJoin", - "allowNewGameplayBindings", - "allowNewInstanceStarts")) facts.put(flag, true); - facts.put( - "quotas", - Map.of( - "maxActiveSessions", - "3", - "maxConcurrentGameInstances", - "2", - "maxStorageBytes", - "4096")); - facts.put("entitlementVersion", "1"); - facts.put("tenantBillingSequence", "1"); - facts.put("tenantAuthorityGeneration", "2"); - return facts; - } - - private static Map sources() { - Map source = new LinkedHashMap<>(); - source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); - source.put("paidReceiptValidUntil", null); - for (String key : - List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) - source.put(key, REQUEST.toString()); - for (String key : - List.of( - "callerTokenSha256", - "callerRegistryRecordSha256", - "callerCommitProofSha256", - "admissionPointerSnapshotDigest")) source.put(key, HASH); - for (String key : - List.of( - "scopeDigest", - "entitlementSourceDigest", - "gameSessionOwnerProofDigest", - "publishedPolicySetDigest", - "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); - source.put("worldRowVersion", "0"); - return source; - } - - private static Snapshot membership() { - String requestDigest = - GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); - var source = - new FreshTenantCreationEvidence( - 1, - "prod", - REQUEST, - REQUEST, - requestDigest, - TENANT, - 17, - "world", - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); - var request = - new TenantAuthorityEventV1Codec.AuthorityRequest( - REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); - var billing = - new TenantAuthorityEventV1Codec.BillingReceipt( - TENANT, - REQUEST, - "sha256:" + HASH, - TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), - 1, - TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), - "sha256:" + HASH); - var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); - String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; - var tuple = - new AuthorityTuple( - "1", - "1", - Map.of(TENANT.toString(), "2"), - Map.of(TENANT.toString(), "1"), - List.of(), - Optional.empty(), - Optional.of( - Map.of( - TENANT.toString(), - new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); - return new Snapshot( - "firemud-account-service", - ACCOUNT.toString(), - TENANT.toString(), - false, - "MISSING", - false, - Map.of(TENANT.toString(), "1"), - "1", - List.of(), - tuple, - "1", - List.of( - new Checkpoint(prefix + "account/" + ACCOUNT, "0"), - new Checkpoint(prefix + "issuer/firemud-account-service", "0"), - new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), - new Checkpoint(event.outboxStreamKey(), "1")), - List.of( - new SourceEvidence( - event.outboxStreamKey(), - "1", - event.eventId().toString(), - event.eventDigest(), - new String(event.payload(), StandardCharsets.UTF_8)))); - } -} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java deleted file mode 100644 index 4ef24c0535..0000000000 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java +++ /dev/null @@ -1,161 +0,0 @@ -package net.firedevops.firemud.common.account.authority; - -import com.google.protobuf.ByteString; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import net.firedevops.firemud.account.v1.PlayerAdmissionEntitlementReadSelectors; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; - -/** Closed comparison and content mapping; this codec authenticates neither callers nor sources. */ -public final class RuntimePlayerAdmissionEntitlementGrpcCodec { - public static final int MAX_REQUEST_WIRE_BYTES = 40 * 1024; - public static final int MAX_RESPONSE_WIRE_BYTES = - RuntimePlayerAdmissionEntitlementEvidence.MAX_CANONICAL_BYTES + MAX_REQUEST_WIRE_BYTES + 32; - public static final long CALL_DEADLINE_SECONDS = 45L; - - private RuntimePlayerAdmissionEntitlementGrpcCodec() {} - - public record Request(RetainedTargetSelector target, String connectScopeId) { - public Request { - Objects.requireNonNull(target, "Exact retained target selectors required"); - if (connectScopeId == null - || connectScopeId.isBlank() - || connectScopeId.length() - > RuntimePlayerAdmissionEntitlementEvidence.MAX_CONNECT_SCOPE_CHARS) throw invalid(); - } - - public String expectedGameSessionWorkload() { - return "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"; - } - - @Override - public String toString() { - return "PlayerAdmissionEntitlementSelectors[redacted]"; - } - } - - /** Process-local credential carrier only; never include in logs or a persisted operation. */ - public record PresentedRequest(Request request, String initialLoginJwt) { - public PresentedRequest { - Objects.requireNonNull(request); - if (initialLoginJwt == null - || initialLoginJwt.isBlank() - || initialLoginJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES - || !initialLoginJwt.matches("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+")) - throw invalid(); - } - - @Override - public String toString() { - return "PlayerAdmissionEntitlementCredential[redacted]"; - } - } - - public static ReadPlayerAdmissionEntitlementRequest toRequest( - Request request, String initialLoginJwt) { - new PresentedRequest(request, initialLoginJwt); - var wire = - ReadPlayerAdmissionEntitlementRequest.newBuilder() - .addSelectors(selectors(request)) - .addInitialLoginJwt(initialLoginJwt) - .build(); - if (wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) throw invalid(); - return wire; - } - - public static PresentedRequest parseRequest(ReadPlayerAdmissionEntitlementRequest wire) { - if (wire == null - || wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES - || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); - return new PresentedRequest( - parseSelectors(one(wire.getSelectorsList())), one(wire.getInitialLoginJwtList())); - } - - public static ReadPlayerAdmissionEntitlementResponse toResponse( - Request request, RuntimePlayerAdmissionEntitlementEvidence evidence) { - requireBinding(request, evidence); - var wire = - ReadPlayerAdmissionEntitlementResponse.newBuilder() - .addRequest(selectors(request)) - .addCanonicalEvidence(ByteString.copyFrom(evidence.canonicalBytes())) - .build(); - if (wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) throw invalid(); - return wire; - } - - public static RuntimePlayerAdmissionEntitlementEvidence requireResponse( - Request expected, ReadPlayerAdmissionEntitlementResponse wire) { - Objects.requireNonNull(expected); - if (wire == null - || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES - || !wire.getUnknownFields().asMap().isEmpty() - || !expected.equals(parseSelectors(one(wire.getRequestList())))) throw invalid(); - var evidence = - RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( - one(wire.getCanonicalEvidenceList()).toByteArray()); - requireBinding(expected, evidence); - return evidence; - } - - private static PlayerAdmissionEntitlementReadSelectors selectors(Request request) { - return PlayerAdmissionEntitlementReadSelectors.newBuilder() - .addSchemaVersion(1) - .addTarget( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( - request.target())) - .addConnectScopeId(request.connectScopeId()) - .build(); - } - - private static Request parseSelectors(PlayerAdmissionEntitlementReadSelectors wire) { - if (wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES - || !wire.getUnknownFields().asMap().isEmpty() - || one(wire.getSchemaVersionList()) != 1) throw invalid(); - return new Request( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( - one(wire.getTargetList())), - one(wire.getConnectScopeIdList())); - } - - private static void requireBinding( - Request request, RuntimePlayerAdmissionEntitlementEvidence evidence) { - Map fields = Objects.requireNonNull(evidence).fields(); - var target = request.target(); - if (!target.accountId().toString().equals(fields.get("callerAccountId")) - || !target.tenantId().toString().equals(fields.get("tenantId")) - || !target.readRequestId().toString().equals(fields.get("requestId")) - || !request.expectedGameSessionWorkload().equals(fields.get("callerWorkload")) - || !request.connectScopeId().equals(fields.get("verifiedConnectScopeId"))) throw invalid(); - if (!(fields.get("target") instanceof Map actual) - || !target.targetNamespace().equals(actual.get("targetNamespace")) - || !target.tenantId().toString().equals(actual.get("tenantId")) - || !target.tenantSlug().equals(actual.get("tenantSlug")) - || !target.worldSlug().equals(actual.get("worldSlug")) - || !target.realmId().toString().equals(actual.get("realmId")) - || !target.realmSlug().equals(actual.get("realmSlug")) - || !target - .playableStateNamespaceId() - .toString() - .equals(actual.get("playableStateNamespaceId")) - || !target.playableStateScope().equals(actual.get("playableStateScope")) - || !target.gameInstanceId().toString().equals(actual.get("gameInstanceId")) - || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) - || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion"))) - throw invalid(); - } - - private static T one(List values) { - if (values.size() != 1) throw invalid(); - return values.getFirst(); - } - - private static IllegalArgumentException invalid() { - return new IllegalArgumentException( - "Exact bounded player-admission entitlement evidence required"); - } -} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java deleted file mode 100644 index 7d19d96322..0000000000 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java +++ /dev/null @@ -1,279 +0,0 @@ -package net.firedevops.firemud.common.account.authority; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import org.junit.jupiter.api.Test; - -/** Controlled content and wire fixtures only; no source authentication or owner execution. */ -class RuntimePlayerAdmissionEntitlementGrpcCodecTest { - private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); - private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); - private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; - private static final String HASH = "a".repeat(64); - private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); - private static final String TOKEN = "controlled.initial.jwt"; - - private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( - UUID account, UUID requestId) { - return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( - new RetainedTargetSelector( - requestId, - account, - "prod", - TENANT, - "tenant", - "world", - REQUEST, - "production", - REQUEST, - "SHARED", - REQUEST, - 7, - 3), - "controlled-scope"); - } - - @Test - void exactRoundTripPreservesSelectorsAndNeverEchoesCredential() { - var request = request(ACCOUNT, REQUEST); - var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); - var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); - assertThat(presented.request()).isEqualTo(request); - assertThat(presented.initialLoginJwt()).isEqualTo(TOKEN); - assertThat(presented.toString()).doesNotContain(TOKEN, "controlled-scope"); - assertThat(request.toString()).doesNotContain("controlled-scope"); - var value = capture(target(), facts(), sources(), NOW); - var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); - assertThat(RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response)) - .isEqualTo(value); - assertThat(response.toByteString().toStringUtf8()).doesNotContain(TOKEN); - } - - @Test - void missingDuplicateUnknownAndOversizedMembersAreRejected() { - var request = request(ACCOUNT, REQUEST); - var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); - var unknown = - com.google.protobuf.UnknownFieldSet.newBuilder() - .addField( - 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build(); - for (var malformed : - List.of( - wire.getDefaultInstanceForType(), - wire.toBuilder().addSelectors(wire.getSelectors(0)).build(), - wire.toBuilder().addInitialLoginJwt(TOKEN).build(), - wire.toBuilder().setUnknownFields(unknown).build(), - wire.toBuilder() - .setSelectors(0, wire.getSelectors(0).toBuilder().addSchemaVersion(1)) - .build(), - wire.toBuilder() - .setSelectors(0, wire.getSelectors(0).toBuilder().setUnknownFields(unknown)) - .build(), - wire.toBuilder().setInitialLoginJwt(0, "a".repeat(45000)).build())) { - assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(malformed)) - .isInstanceOf(IllegalArgumentException.class); - } - var response = - RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( - request, capture(target(), facts(), sources(), NOW)); - for (var malformed : - List.of( - response.getDefaultInstanceForType(), - response.toBuilder().addRequest(response.getRequest(0)).build(), - response.toBuilder().addCanonicalEvidence(response.getCanonicalEvidence(0)).build(), - response.toBuilder().setUnknownFields(unknown).build(), - response.toBuilder() - .setCanonicalEvidence(0, com.google.protobuf.ByteString.copyFromUtf8("{}")) - .build())) { - assertThatThrownBy( - () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, malformed)) - .isInstanceOf(IllegalArgumentException.class); - } - } - - @Test - void changedCallerRequestOrScopeCannotBeReturnedAsCorrelatedEvidence() { - var request = request(ACCOUNT, REQUEST); - var value = capture(target(), facts(), sources(), NOW); - var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); - for (var other : - List.of( - request(UUID.randomUUID(), REQUEST), - request(ACCOUNT, UUID.randomUUID()), - new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( - request.target(), "another-scope"))) { - assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(other, value)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(other, response)) - .isInstanceOf(IllegalArgumentException.class); - } - } - - private static RuntimePlayerAdmissionEntitlementEvidence capture( - Map target, - Map facts, - Map source, - Instant at) { - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); - } - - private static Map target() { - Map target = new LinkedHashMap<>(); - target.put("targetClass", "PUBLIC_PRODUCTION"); - target.put("characterCreationPolicy", "PRESEEDED_ONLY"); - target.put("targetNamespace", "prod"); - target.put("tenantId", TENANT.toString()); - target.put("tenantSlug", "tenant"); - target.put("worldSlug", "world"); - target.put("realmId", REQUEST.toString()); - target.put("realmSlug", "production"); - target.put("playableStateNamespaceId", REQUEST.toString()); - target.put("playableStateScope", "SHARED"); - target.put("gameInstanceId", REQUEST.toString()); - target.put("canonicalVersionId", REQUEST.toString()); - target.put("catalogRevision", "7"); - target.put("pointerVersion", "3"); - target.put("activeWorldEpoch", "5"); - target.put("evaluatedAt", NOW.minusSeconds(20).toString()); - target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); - return target; - } - - private static Map facts() { - Map facts = new LinkedHashMap<>(); - facts.put("sourceKind", "NON_PAID_DEMO"); - facts.put("subscriptionStatus", null); - facts.put("provisioningStatus", null); - for (String flag : - List.of( - "gameplayAvailable", - "allowPublicJoin", - "allowNewGameplayBindings", - "allowNewInstanceStarts")) facts.put(flag, true); - facts.put( - "quotas", - Map.of( - "maxActiveSessions", - "3", - "maxConcurrentGameInstances", - "2", - "maxStorageBytes", - "4096")); - facts.put("entitlementVersion", "1"); - facts.put("tenantBillingSequence", "1"); - facts.put("tenantAuthorityGeneration", "2"); - return facts; - } - - private static Map sources() { - Map source = new LinkedHashMap<>(); - source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); - source.put("paidReceiptValidUntil", null); - for (String key : - List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) - source.put(key, REQUEST.toString()); - for (String key : - List.of( - "callerTokenSha256", - "callerRegistryRecordSha256", - "callerCommitProofSha256", - "admissionPointerSnapshotDigest")) source.put(key, HASH); - for (String key : - List.of( - "scopeDigest", - "entitlementSourceDigest", - "gameSessionOwnerProofDigest", - "publishedPolicySetDigest", - "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); - source.put("worldRowVersion", "0"); - return source; - } - - private static Snapshot membership() { - String requestDigest = - GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); - var source = - new FreshTenantCreationEvidence( - 1, - "prod", - REQUEST, - REQUEST, - requestDigest, - TENANT, - 17, - "world", - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); - var request = - new TenantAuthorityEventV1Codec.AuthorityRequest( - REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); - var billing = - new TenantAuthorityEventV1Codec.BillingReceipt( - TENANT, - REQUEST, - "sha256:" + HASH, - TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), - 1, - TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), - "sha256:" + HASH); - var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); - String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; - var tuple = - new AuthorityTuple( - "1", - "1", - Map.of(TENANT.toString(), "2"), - Map.of(TENANT.toString(), "1"), - List.of(), - Optional.empty(), - Optional.of( - Map.of( - TENANT.toString(), - new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); - return new Snapshot( - "firemud-account-service", - ACCOUNT.toString(), - TENANT.toString(), - false, - "MISSING", - false, - Map.of(TENANT.toString(), "1"), - "1", - List.of(), - tuple, - "1", - List.of( - new Checkpoint(prefix + "account/" + ACCOUNT, "0"), - new Checkpoint(prefix + "issuer/firemud-account-service", "0"), - new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), - new Checkpoint(event.outboxStreamKey(), "1")), - List.of( - new SourceEvidence( - event.outboxStreamKey(), - "1", - event.eventId().toString(), - event.eventDigest(), - new String(event.payload(), StandardCharsets.UTF_8)))); - } -} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index c2bd44fa92..ab2b77fa28 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -187,14 +187,10 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture*.class") - include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture*.class") - include("net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture*.class") } from("src/main/resources") { - include("redis/lua/game-session-initial-context-cas.lua") - include("redis/scripts/game-session-initial-context-cas.json") include("redis/lua/game-session-issuer-bootstrap-partition-build.lua") include("redis/scripts/game-session-issuer-bootstrap-partition-build.json") include("redis/lua/game-session-issuer-binding-local-add.lua") diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java deleted file mode 100644 index 7d88cf4ae2..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java +++ /dev/null @@ -1,393 +0,0 @@ -package net.firedevops.firemud.gamesession.client; - -import io.grpc.Context; -import io.grpc.Deadline; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Clock; -import java.time.Instant; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; -import java.util.function.Supplier; -import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; -import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; -import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; -import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; - -/** - * Manually composed Account PLAYER_ADMISSION read. The caller supplies an owned canonical scope and - * live LOGIN custody; this client contributes no admission decision or hold. - */ -public final class AccountPlayerAdmissionEntitlementClient - extends AbstractReloadingBlockingGrpcClient< - AccountPlayerAdmissionEntitlementReadServiceGrpc - .AccountPlayerAdmissionEntitlementReadServiceBlockingStub> { - private final String namespace; - private final String expectedAccountPeer; - private final Clock clock; - - public AccountPlayerAdmissionEntitlementClient( - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tls, - GrpcChannelFactory channels, - String workloadNamespace, - Clock clock) { - super( - endpoints, - requireFileBackedMtls(tls, "Player-admission entitlement read"), - channels, - AccountPlayerAdmissionEntitlementClient.class); - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { - throw new IllegalArgumentException("Fixed Game Session workload namespace required"); - } - this.namespace = workloadNamespace; - this.expectedAccountPeer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; - this.clock = Objects.requireNonNull(clock, "Clock required"); - } - - /** Initializes this workflow-owned client outside any ambient SQL transaction. */ - public void init() throws IOException { - requireNoAmbientSql( - "Player-admission entitlement client initialization requires no ambient SQL"); - initOnce("Player-admission entitlement client is closed", "Account read unavailable"); - } - - /** - * Reads the exact current Account value for one verified first-party scope and LOGIN result. The - * token is disclosed only by the generated request after exact same-namespace Account mTLS peer - * verification. This read supplies no World hold and never persists LOGIN custody. - */ - public RuntimePlayerAdmissionEntitlementEvidence read( - FirstPartyConnectContext verifiedContext, - UUID readRequestId, - CanonicalGameplayLoginResult loginCustody, - BooleanSupplier loginCustodyCurrent) { - return read( - readRequestId, - loginCustody, - loginCustodyCurrent, - () -> request(verifiedContext, readRequestId), - () -> request(verifiedContext, readRequestId), - evidence -> - requireTargetBinding( - evidence, - verifiedContext.resolvedTarget(), - Instant.ofEpochMilli(verifiedContext.claims().expiresAtMillis()).toString())); - } - - /** - * Borrows an Account-issued direct-text lobby scope inside its owner's current custody callback. - * Retaining or decoding the scope never establishes that custody; this read installs no context. - */ - public RuntimePlayerAdmissionEntitlementEvidence read( - DirectTextAuthenticatedLobbyScope scope, - InitialGameplayLoginAttemptCoordinates original, - ObservedDirectTextTransport transport, - UUID readRequestId, - CanonicalGameplayLoginResult loginCustody, - BooleanSupplier loginCustodyCurrent) { - return read( - readRequestId, - loginCustody, - loginCustodyCurrent, - () -> { - if (scope == null) throw invalid(); - scope.requireCurrent(original, loginCustody, transport, clock); - }, - () -> - request( - scope.publicTarget(), - scope.evidence().accountId(), - scope.issued().connectScopeId(), - readRequestId), - evidence -> - requireTargetBinding( - evidence, scope.publicTarget(), scope.issued().connectScopeExpiresAt())); - } - - private RuntimePlayerAdmissionEntitlementEvidence read( - UUID readRequestId, - CanonicalGameplayLoginResult loginCustody, - BooleanSupplier loginCustodyCurrent, - Runnable requireScopeCurrent, - Supplier requestSource, - Consumer requireResponseTarget) { - requireNoAmbientSql("Player-admission entitlement RPC requires no ambient SQL"); - Deadline overall = - Deadline.after( - RuntimePlayerAdmissionEntitlementGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); - if (Context.current().getDeadline() != null) { - overall = overall.minimum(Context.current().getDeadline()); - } - if (!v4(readRequestId)) { - throw invalid(); - } - requireCurrent(loginCustodyCurrent, requireScopeCurrent); - if (overall.isExpired()) { - throw failure(Status.Code.DEADLINE_EXCEEDED); - } - - var request = requestSource.get(); - var login = requireLiveLogin(loginCustody, request.target().accountId()); - byte[] compactJwt = null; - try { - compactJwt = loginCustody.compactJwtBytes(); - requireCurrent(loginCustodyCurrent, requireScopeCurrent); - if (overall.isExpired()) { - throw failure(Status.Code.DEADLINE_EXCEEDED); - } - if (!isBoundedAsciiJwt(compactJwt) || !matchesSha256(compactJwt, login.tokenSha256())) { - throw invalid(); - } - String compact = new String(compactJwt, StandardCharsets.US_ASCII); - var wireRequest = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, compact); - var stub = - requireInitializedStub("Account player-admission entitlement client is unavailable") - .withDeadline(overall) - .withMaxOutboundMessageSize( - RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES) - .withMaxInboundMessageSize( - RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES); - // Recheck immediately before invoking gRPC; the call credentials independently gate body - // release on the exact authenticated Account peer. - requireCurrent(loginCustodyCurrent, requireScopeCurrent); - if (overall.isExpired()) { - throw failure(Status.Code.DEADLINE_EXCEEDED); - } - var response = stub.readPlayerAdmissionEntitlement(wireRequest); - requireCurrent(loginCustodyCurrent, requireScopeCurrent); - requireLiveLogin(loginCustody, request.target().accountId()); - var evidence = RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response); - requireResponseTarget.accept(evidence); - requireLoginBinding(evidence, login); - requireCurrent(loginCustodyCurrent, requireScopeCurrent); - requireLiveLogin(loginCustody, request.target().accountId()); - evidence.requireCurrentAt(clock.instant()); - return evidence; - } catch (StatusRuntimeException transport) { - throw failure(transport.getStatus().getCode()); - } finally { - if (compactJwt != null) { - Arrays.fill(compactJwt, (byte) 0); - } - } - } - - private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( - FirstPartyConnectContext context, UUID readRequestId) { - try { - if (context == null || !context.hasCompleteRoutingScope()) { - throw invalid(); - } - var claims = context.claims(); - UUID accountId = UUID.fromString(context.accountId()); - if (!v4(accountId) - || claims.expiresAtMillis() <= clock.millis() - || context.connectScopeId() == null - || context.connectScopeId().isBlank()) { - throw invalid(); - } - return request(context.resolvedTarget(), accountId, context.connectScopeId(), readRequestId); - } catch (RuntimeException invalidContext) { - throw invalid(); - } - } - - private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( - CanonicalPlayableTarget target, UUID accountId, String connectScopeId, UUID readRequestId) { - if (target == null - || !namespace.equals(target.targetNamespace()) - || !"SHARED".equals(target.playableStateScope()) - || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) - || target.positiveDurableAbort() - || !v4(accountId)) throw invalid(); - var selector = - new RetainedTargetSelector( - readRequestId, - accountId, - target.targetNamespace(), - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion()); - return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request(selector, connectScopeId); - } - - private CanonicalGameplayLoginResult.NonSecretEvidence requireLiveLogin( - CanonicalGameplayLoginResult custody, UUID expectedAccount) { - try { - if (custody == null) { - throw invalid(); - } - var evidence = custody.evidence(); - long now = clock.instant().getEpochSecond(); - if (evidence == null - || !expectedAccount.equals(evidence.accountId()) - || !GameSessionAccountDelegationProfile.PROFILE.equals(evidence.tokenProfile()) - || evidence.issuedAtEpochSecond() > now - || evidence.notBeforeEpochSecond() > now - || evidence.expiresAtEpochSecond() <= now) { - throw invalid(); - } - return evidence; - } catch (RuntimeException invalidCustody) { - throw invalid(); - } - } - - private static void requireLoginBinding( - RuntimePlayerAdmissionEntitlementEvidence evidence, - CanonicalGameplayLoginResult.NonSecretEvidence login) { - Object rawSources = evidence.fields().get("sourceReferences"); - if (!(rawSources instanceof Map sources) - || !login.tokenJti().toString().equals(sources.get("callerTokenJti")) - || !login.tokenSha256().equals(sources.get("callerTokenSha256")) - || !login.callerContextId().toString().equals(sources.get("callerContextId"))) { - throw invalid(); - } - } - - private static void requireTargetBinding( - RuntimePlayerAdmissionEntitlementEvidence evidence, - CanonicalPlayableTarget target, - String connectScopeExpiresAt) { - Object rawTarget = evidence.fields().get("target"); - Object rawSources = evidence.fields().get("sourceReferences"); - if (!(rawTarget instanceof Map actual) - || !(rawSources instanceof Map sources) - || !"PUBLIC_PRODUCTION".equals(actual.get("targetClass")) - || !"PRESEEDED_ONLY".equals(actual.get("characterCreationPolicy")) - || !target.targetNamespace().equals(actual.get("targetNamespace")) - || !target.canonicalTenantId().toString().equals(actual.get("tenantId")) - || !target.tenantSlug().equals(actual.get("tenantSlug")) - || !target.worldSlug().equals(actual.get("worldSlug")) - || !target.realmId().toString().equals(actual.get("realmId")) - || !target.realmSlug().equals(actual.get("realmSlug")) - || !target - .playableStateNamespaceId() - .toString() - .equals(actual.get("playableStateNamespaceId")) - || !target.playableStateScope().equals(actual.get("playableStateScope")) - || !target.canonicalGameInstanceId().toString().equals(actual.get("gameInstanceId")) - || !target.canonicalVersionId().toString().equals(actual.get("canonicalVersionId")) - || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) - || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion")) - || !Long.toString(target.activeWorldEpoch()).equals(actual.get("activeWorldEpoch")) - || !connectScopeExpiresAt.equals(actual.get("connectScopeExpiresAt")) - || !target - .admissionPointerSnapshotDigest() - .equals(sources.get("admissionPointerSnapshotDigest")) - || !target.ownerProofDigest().equals(sources.get("gameSessionOwnerProofDigest"))) { - throw invalid(); - } - } - - private boolean isBoundedAsciiJwt(byte[] bytes) { - if (bytes == null - || bytes.length == 0 - || bytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { - return false; - } - for (byte value : bytes) { - if (value < 0x21 || value > 0x7e) { - return false; - } - } - return true; - } - - private static boolean matchesSha256(byte[] value, String expected) { - byte[] digest = null; - try { - digest = MessageDigest.getInstance("SHA-256").digest(value); - return HexFormat.of().formatHex(digest).equals(expected); - } catch (NoSuchAlgorithmException unavailable) { - return false; - } finally { - if (digest != null) { - Arrays.fill(digest, (byte) 0); - } - } - } - - private static boolean current(BooleanSupplier custodyCurrent) { - try { - return custodyCurrent != null && custodyCurrent.getAsBoolean(); - } catch (RuntimeException unavailable) { - return false; - } - } - - private static void requireCurrent(BooleanSupplier custodyCurrent, Runnable requireScopeCurrent) { - if (!current(custodyCurrent) || Context.current().isCancelled()) { - throw failure(Status.Code.CANCELLED); - } - requireScopeCurrent.run(); - } - - private static boolean v4(UUID value) { - return value != null && value.version() == 4 && value.variant() == 2; - } - - @Override - protected String configuredTarget(ServiceEndpointsProperties endpoints) { - return endpoints.getAccountService(); - } - - @Override - protected String defaultTarget() { - return "account-service:6565"; - } - - @Override - protected AccountPlayerAdmissionEntitlementReadServiceGrpc - .AccountPlayerAdmissionEntitlementReadServiceBlockingStub - buildStub(ManagedChannel channel) { - return AccountPlayerAdmissionEntitlementReadServiceGrpc.newBlockingStub(channel) - .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedAccountPeer)) - .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)) - .withCompression("gzip"); - } - - private static IllegalArgumentException invalid() { - return new IllegalArgumentException( - "Exact live LOGIN custody and verified player-admission scope required"); - } - - private static StatusRuntimeException failure(Status.Code code) { - return Status.fromCode(code) - .withDescription("Account player-admission entitlement read did not complete") - .asRuntimeException(); - } -} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java deleted file mode 100644 index 7ec6ed0f27..0000000000 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import io.grpc.BindableService; -import io.grpc.ServerInterceptors; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; -import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; -import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; -import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; -import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; -import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; -import org.jooq.DSLContext; - -/** - * Assembles actual current Game Session source readers over caller-owned PostgreSQL state. The - * caller owns source provenance, authenticated clients, socket identity and cleanup. This fixture - * creates no rows, changes no registration and does not authorize gameplay admission. - */ -public final class CanonicalPublishedAdmissionActualOwnerCompositionFixture { - private CanonicalPublishedAdmissionActualOwnerCompositionFixture() {} - - public static BindableService receiver( - DSLContext dsl, - String namespace, - GameDesignPublishedRealmPolicyClient policies, - WorldCanonicalInstanceLifecycleClient world) { - var catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); - var admissions = - new CanonicalInitialAdmissionRepository( - dsl, - catalogs, - new GameSessionCanonicalAdmissionPointerRepository( - dsl, catalogs, new GameplayAdmissionPointerEventRepository(dsl))); - var launches = new CanonicalGameInstanceLaunchAssociationRepository(dsl, namespace); - var routes = new CanonicalPlayerRouteReadService(namespace, catalogs, admissions, launches); - var published = - new CanonicalPublishedPlayerRouteReadService( - namespace, routes, catalogs, launches, policies); - var guard = new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(namespace); - var receiver = - new CanonicalGameplayAdmissionDecisionReadGrpcService( - new CanonicalGameplayBindingInventoryRepository(dsl), - guard, - namespace, - null, - routes, - published, - launches, - world); - return () -> ServerInterceptors.intercept(receiver, guard); - } -} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java deleted file mode 100644 index 0c778a8049..0000000000 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java +++ /dev/null @@ -1,410 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.api.sync.RedisCommands; -import io.lettuce.core.codec.ByteArrayCodec; -import io.lettuce.core.output.StatusOutput; -import io.lettuce.core.protocol.CommandArgs; -import io.lettuce.core.protocol.CommandKeyword; -import io.lettuce.core.protocol.CommandType; -import io.lettuce.core.protocol.ProtocolVersion; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; -import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; -import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; -import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; -import org.jooq.DSLContext; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * Actual original journal, PENDING, Account client and INSTALLED composition over borrowed physical - * stores. Credential delivery and external Redis qualification remain controlled. The caller must - * finish earlier users of the GS Redis principal before opening this fixture; no active sibling - * connections are reset. The decoded readback is historical evidence, not receiving custody, - * current token authority, gameplay admission or a production qualification provider. - */ -@SuppressWarnings("resource") -public final class InitialGameplayLoginPhysicalCompositionFixture implements AutoCloseable { - private static final String PRINCIPAL = InitialGameplayLoginRedisBinding.PRINCIPAL; - private static final String BINDING = "controlled-physical-initial-login-primary"; - private final InitialGameplayLoginCoordinationJournalRepository journal; - private final RedisClient writer; - private final List mutations = new ArrayList<>(); - private final List journalObservations = new ArrayList<>(); - private InitialGameplayLoginOwner.Outcome outcome; - private CanonicalGameplayLoginResult loginResult; - private InitialGameplayLoginContextState installedReadback; - private boolean closed; - - /** - * Transfers the mutable OTP buffer, but borrows the already migrated SQL owners, initialized - * actual Account client and test-owned AOF primary/replica. No listener or runtime bean is added. - */ - public static InitialGameplayLoginPhysicalCompositionFixture open( - DSLContext gs, - PlatformTransactionManager transactionManager, - String redisHost, - int redisPort, - CanonicalGameplayLoginAccountClient account, - String email, - String canonicalClientAddress, - char[] ownedOtp) { - Objects.requireNonNull(ownedOtp, "Owned credential buffer required"); - InitialGameplayLoginPhysicalCompositionFixture fixture = null; - try (var credentials = - new InitialGameplayLoginCredentialPresentation(email, canonicalClientAddress, ownedOtp)) { - fixture = new InitialGameplayLoginPhysicalCompositionFixture(gs, redisHost, redisPort); - fixture.receive(transactionManager, account, credentials); - assertThat(Arrays.equals(ownedOtp, new char[ownedOtp.length])).isTrue(); - return fixture; - } catch (RuntimeException | Error failure) { - if (fixture != null) { - try { - fixture.close(); - } catch (RuntimeException | Error cleanup) { - failure.addSuppressed(cleanup); - } - } - throw failure; - } finally { - Arrays.fill(ownedOtp, '\0'); - } - } - - private InitialGameplayLoginPhysicalCompositionFixture( - DSLContext gs, String redisHost, int redisPort) { - var actualJournal = new InitialGameplayLoginCoordinationJournalRepository(gs); - // Observation only: every method delegates to the unchanged real SQL owner. - journal = - org.mockito.Mockito.mock( - InitialGameplayLoginCoordinationJournalRepository.class, - invocation -> { - String operation = invocation.getMethod().getName(); - try { - Object result = - invoke(actualJournal, invocation.getMethod(), invocation.getArguments()); - journalObservations.add(operation + ":OK"); - return result; - } catch (Throwable failure) { - String sqlState = - failure instanceof org.jooq.exception.DataAccessException sql - ? sql.sqlState() - : "none"; - journalObservations.add( - operation + ":" + failure.getClass().getSimpleName() + ":" + sqlState); - throw failure; - } - }); - String password = UUID.randomUUID().toString(); - configureOwnedPrincipal(redisHost, redisPort, password); - writer = redis(redisHost, redisPort, PRINCIPAL, password); - } - - private void receive( - PlatformTransactionManager transactionManager, - CanonicalGameplayLoginAccountClient account, - InitialGameplayLoginCredentialPresentation credentials) { - var contexts = - new InitialGameplayLoginContextRedisClient( - new InitialGameplayLoginRedisBinding( - BINDING, - this::observedConnection, - new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 5_000)), - RedisScriptCatalog.fromContributions( - List.of(new InitialGameplayLoginRedisScriptContribution())), - new ControlledQualification()); - var cleanup = - new InitialGameplayLoginCleanupOwner( - journal, - new InitialGameplayLoginRedisAttemptClosure(contexts), - account, - transactionManager); - outcome = new InitialGameplayLoginOwner(contexts, cleanup, account).receive(credentials); - assertThat(outcome.status()) - .as( - "Initial LOGIN failureCode=%s journal=%s mutations=%s", - outcome.failureCode(), journalObservations, mutations) - .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); - loginResult = outcome.takePrivateResult().orElseThrow(); - assertThat(mutations).containsExactly("CREATE_PENDING", "INSTALL"); - installedReadback = physicalReadback(); - assertThat(installedReadback.state()) - .isEqualTo(InitialGameplayLoginContextState.State.INSTALLED); - assertThat(installedReadback.evidence()).isEqualTo(loginResult.evidence()); - var retained = journal.readCommitted(coordinates()).orElseThrow(); - assertThat(retained.abandoned()).isFalse(); - assertThat(retained.verifiedWitness()).contains(witness(installedReadback)); - assertThat(retained.frozenRetirementRequest()).isEmpty(); - byte[] compact = loginResult.compactJwtBytes(); - try { - assertThat(containsSequence(installedReadback.encode(), compact)).isFalse(); - } finally { - Arrays.fill(compact, (byte) 0); - } - } - - public InitialGameplayLoginAttemptCoordinates coordinates() { - return outcome.coordinates(); - } - - /** The actual owner outcome, retained for explicit pre-admission custody-loss cleanup. */ - public InitialGameplayLoginOwner.Outcome outcome() { - return outcome; - } - - /** Borrow the actual transferred result; the fixture retains its cleanup responsibility. */ - public CanonicalGameplayLoginResult loginResult() { - return loginResult; - } - - /** Historical physical installation evidence only; this does not authenticate current custody. */ - public InitialGameplayLoginContextState installedReadback() { - return installedReadback; - } - - /** - * Call before shutting down Account transport; known-token disposal uses that actual receiver. - */ - public InitialGameplayLoginCleanupOwner.CleanupObservation abandonOriginalAfterCustodyLoss() { - var observation = outcome.abandonOriginalAfterCustodyLoss(); - assertThat(physicalReadback().state()).isEqualTo(InitialGameplayLoginContextState.State.CLOSED); - var retained = journal.readCommitted(coordinates()).orElseThrow(); - assertThat(retained.abandoned()).isTrue(); - assertThat(retained.frozenRetirementRequest()).isPresent(); - assertThat(retained.frozenRetirementRequest().orElseThrow().getTokenWitness()) - .isEqualTo(witness(installedReadback)); - assertThatThrownBy(loginResult::compactJwtBytes).isInstanceOf(IllegalStateException.class); - return observation; - } - - private InitialGameplayLoginContextState physicalReadback() { - try (var connection = writer.connect(ByteArrayCodec.INSTANCE)) { - var commands = connection.sync(); - assertThat(commands.aclWhoami()).isEqualTo(PRINCIPAL); - byte[] key = key(coordinates()); - var decoded = InitialGameplayLoginContextState.decode(commands.get(key)); - assertThat(decoded.coordinates()).isEqualTo(coordinates()); - assertThat(commands.pttl(key)).isEqualTo(-1L); - return decoded; - } - } - - /** Every command still delegates to the real pinned physical connection. */ - @SuppressWarnings("unchecked") - private StatefulRedisConnection observedConnection() { - var connection = writer.connect(ByteArrayCodec.INSTANCE); - return (StatefulRedisConnection) - Proxy.newProxyInstance( - StatefulRedisConnection.class.getClassLoader(), - new Class[] {StatefulRedisConnection.class}, - (proxy, method, args) -> { - if (!method.getName().equals("sync")) return invoke(connection, method, args); - var commands = connection.sync(); - return Proxy.newProxyInstance( - RedisCommands.class.getClassLoader(), - new Class[] {RedisCommands.class}, - (commandProxy, command, arguments) -> { - if (command.getName().equals("evalsha")) { - beforeMutation(commands, (byte[][]) arguments[2], (byte[][]) arguments[3]); - } - return invoke(commands, command, arguments); - }); - }); - } - - private void beforeMutation( - RedisCommands commands, byte[][] keys, byte[][] args) { - require(keys.length == 1 && args.length == 3); - String operation = new String(args[0], StandardCharsets.US_ASCII); - var desired = InitialGameplayLoginContextState.decode(args[2]); - var original = desired.coordinates(); - require(Arrays.equals(keys[0], key(original))); - var committed = journal.readCommitted(original).orElseThrow(); - require(original.expectedAttemptFence() == 1); - require(!original.requestId().equals(original.callerContextId())); - if ("CREATE_PENDING".equals(operation)) { - require(mutations.isEmpty()); - require(!committed.abandoned() && committed.verifiedWitness().isEmpty()); - // Observation only: the actual Lua absence check remains the create authority. - require(commands.get(keys[0]) == null); - } else if ("INSTALL".equals(operation)) { - require(mutations.equals(List.of("CREATE_PENDING"))); - require(!committed.abandoned()); - require(committed.verifiedWitness().filter(witness(desired)::equals).isPresent()); - var pending = InitialGameplayLoginContextState.decode(commands.get(keys[0])); - require(pending.coordinates().equals(original)); - require(pending.state() == InitialGameplayLoginContextState.State.PENDING); - } else { - require("CLOSE".equals(operation) && committed.abandoned()); - } - mutations.add(operation); - } - - private static InitialGameplayLoginTokenWitness witness(InitialGameplayLoginContextState state) { - var evidence = state.evidence(); - return InitialGameplayLoginTokenWitness.newBuilder() - .setTokenJti(evidence.tokenJti().toString()) - .setTokenSha256(evidence.tokenSha256()) - .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) - .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) - .build(); - } - - private static Object invoke(Object target, Method method, Object[] arguments) throws Throwable { - try { - return method.invoke(target, arguments); - } catch (InvocationTargetException failure) { - throw failure.getCause(); - } - } - - private static void configureOwnedPrincipal(String host, int port, String password) { - var administrator = redis(host, port, null, null); - try (var connection = administrator.connect(ByteArrayCodec.INSTANCE)) { - var commands = connection.sync(); - require( - commands - .clientList() - .lines() - .noneMatch(line -> line.contains(" user=" + PRINCIPAL + " "))); - commands.aclSetuser( - PRINCIPAL, - new AclSetuserArgs() - .reset() - .on() - .addPassword(password) - .keyPattern(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE + "*") - .addCommand(CommandType.HELLO) - .addCommand(CommandType.PING) - .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) - .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) - .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) - .addCommand(CommandType.EVALSHA) - .addCommand(CommandType.GET) - .addCommand(CommandType.SET) - .addCommand(CommandType.TYPE) - .addCommand(CommandType.PTTL) - .addCommand(CommandType.PEXPIRETIME)); - commands.dispatch( - CommandType.ACL, - new StatusOutput<>(ByteArrayCodec.INSTANCE), - new CommandArgs<>(ByteArrayCodec.INSTANCE).add("SETUSER").add(PRINCIPAL).add("+waitaof")); - } finally { - administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); - } - } - - private static RedisClient redis(String host, int port, String username, String password) { - var builder = RedisURI.Builder.redis(host, port); - if (username != null) builder.withAuthentication(username, password); - var uri = builder.build(); - uri.setTimeout(Duration.ofSeconds(10)); - var client = RedisClient.create(uri); - client.setOptions( - ClientOptions.builder() - .autoReconnect(false) - .protocolVersion(ProtocolVersion.RESP2) - .build()); - return client; - } - - private static byte[] key(InitialGameplayLoginAttemptCoordinates coordinates) { - return InitialGameplayLoginContextRedisKeys.contextKey(coordinates.callerContextId()) - .getBytes(StandardCharsets.US_ASCII); - } - - private static boolean containsSequence(byte[] haystack, byte[] needle) { - for (int offset = 0; offset <= haystack.length - needle.length; offset++) { - if (Arrays.equals(haystack, offset, offset + needle.length, needle, 0, needle.length)) { - return true; - } - } - return false; - } - - private static void require(boolean condition) { - if (!condition) - throw new IllegalStateException("Physical initial LOGIN fixture precondition failed"); - } - - /** Stipulated test authority only, never a production recovery or transport-custody producer. */ - private static final class ControlledQualification - implements InitialGameplayLoginCoordinationQualification { - @Override - public Optional acquire(String scope, String binding) { - require(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE.equals(scope)); - require(BINDING.equals(binding)); - return Optional.of( - new Lease() { - private boolean closed; - - @Override - public String scope() { - return scope; - } - - @Override - public String protectedBindingId() { - return binding; - } - - @Override - public long fence() { - return 37; - } - - @Override - public void requireCurrent() { - require(!closed); - } - - @Override - public void close() { - closed = true; - } - }); - } - } - - /** - * Ends pre-admission private custody before closing owned Redis clients. Retained SQL rows and - * Redis markers stay with the enclosing disposable physical fixture, without a retention bypass. - */ - @Override - public void close() { - if (closed) return; - closed = true; - try { - if (outcome != null - && outcome.status() == InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING - && outcome.custodyLossCleanup().isEmpty()) { - outcome.abandonOriginalAfterCustodyLoss(); - } - } finally { - if (loginResult != null) loginResult.close(); - if (outcome != null) outcome.close(); - writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); - } - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java deleted file mode 100644 index 6ca0218ecb..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ /dev/null @@ -1,783 +0,0 @@ -package net.firedevops.firemud.gamesession.client; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; -import io.grpc.stub.StreamObserver; -import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; -import java.util.function.BooleanSupplier; -import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; -import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; -import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; -import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; -import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; -import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; -import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; -import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; -import net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -/** Controlled Account peer proof for credential release and canonical response binding. */ -@Timeout(90) -class AccountPlayerAdmissionEntitlementClientMtlsTest { - private static final String NAMESPACE = "firemud-test"; - private static final String GS_PEER = - "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; - private static final String ACCOUNT_PEER = - "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; - private static final String JWT = "a.b.c"; - private static final UUID LOGIN_REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); - private static final UUID LOGIN_CONTEXT = UUID.fromString("44444444-4444-4444-8444-444444444444"); - private static final UUID LOGIN_JTI = UUID.fromString("55555555-5555-4555-8555-555555555555"); - private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); - private static final Instant NOW = Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW + 1_000L); - private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); - private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = - new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, LOGIN_CONTEXT, 1); - private static final ObservedDirectTextTransport TRANSPORT = - new ObservedDirectTextTransport( - "00042", UUID.fromString("99999999-9999-4999-8999-999999999999")); - private static final Instant DIRECT_SCOPE_EXPIRY = NOW.plusSeconds(25); - @TempDir static Path directory; - private static LoopbackMtlsTestPki.Pki pki; - - @BeforeAll - static void certificates() throws Exception { - pki = - LoopbackMtlsTestPki.create( - directory, - "Player admission entitlement client test CA", - new LoopbackMtlsTestPki.IdentitySpec("client", GS_PEER, false), - new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT_PEER, true), - new LoopbackMtlsTestPki.IdentitySpec( - "wrong-service", - "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", - true), - new LoopbackMtlsTestPki.IdentitySpec( - "wrong-namespace", "spiffe://firemud/ns/other/sa/account-service", true)); - } - - @Test - void exactAccountPeerReceivesCurrentLoginCredentialAndReturnsBoundCanonicalEvidence() - throws Exception { - var context = context(); - var login = loginCustody(); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); - try (var client = client(server)) { - client.init(); - var result = client.read(context, READ_REQUEST, login, () -> true); - assertThat(result.fields()) - .containsEntry("variant", "PLAYER_ADMISSION") - .containsEntry("sourceKind", "NON_PAID_DEMO") - .containsEntry("membershipExists", false); - assertThat(calls).hasValue(1); - assertThat(observedJwt).hasValue(JWT); - assertThat(observedPeer).hasValue(GS_PEER); - assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); - } finally { - stop(server); - } - } - - @Test - void sameCaWrongServiceAndNamespaceReceiveNoRequestCredential() throws Exception { - for (String identity : List.of("wrong-service", "wrong-namespace")) { - var context = context(); - var login = loginCustody(); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Server server = server(identity, calls, observedJwt, observedPeer, context, login.evidence()); - try (var client = client(server)) { - client.init(); - assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> true)) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - failure -> - assertThat(failure.getStatus().getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); - assertThat(calls).hasValue(0); - assertThat(observedJwt).hasValue(null); - assertThat(observedPeer).hasValue(null); - } finally { - stop(server); - } - } - } - - @Test - void staleLoginCustodyDoesNotStartRpc() throws Exception { - var context = context(); - var login = loginCustody(); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); - try (var client = client(server)) { - client.init(); - assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> false)) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - failure -> - assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.CANCELLED)); - assertThat(calls).hasValue(0); - assertThat(observedJwt).hasValue(null); - } finally { - stop(server); - } - } - - @Test - void directTextOwnedScopeUsesExactAccountExpiryAndCurrentLoginWithoutFirstPartyContext() - throws Exception { - var target = context().resolvedTarget(); - var borrowed = new ArrayList(); - var login = loginCustody(borrowed); - var scope = directTextScope(target, login, DIRECT_SCOPE_EXPIRY); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Server server = - server( - "account", - calls, - observedJwt, - observedPeer, - target, - DIRECT_SCOPE_EXPIRY, - login.evidence(), - (value, sources) -> {}, - () -> {}); - try (var client = client(server)) { - client.init(); - var result = client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true); - assertThat(result.fields()) - .containsEntry("verifiedConnectScopeId", "direct-text-owned-scope"); - assertThat(((Map) result.fields().get("target")).get("connectScopeExpiresAt")) - .isEqualTo(DIRECT_SCOPE_EXPIRY.toString()); - assertThat(calls).hasValue(1); - assertThat(observedJwt).hasValue(JWT); - assertThat(observedPeer).hasValue(GS_PEER); - assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); - assertThat(borrowed) - .isNotEmpty() - .allSatisfy(bytes -> assertThat(bytes).containsOnly((byte) 0)); - } finally { - stop(server); - } - } - - @ParameterizedTest - @ValueSource( - strings = { - "original-request", - "original-context", - "attempt-fence", - "transport-session", - "transport-proxy", - "stale-custody", - "throwing-custody", - "null-custody", - "custody-lost-before-rpc", - "closed-login", - "expired-login", - "expired-scope", - "wrong-namespace", - "private-scope", - "created-policy", - "durable-abort", - "read-correlation" - }) - void directTextInvalidOrStaleInputsDiscloseNoCredential(String change) throws Exception { - var target = context().resolvedTarget(); - switch (change) { - case "wrong-namespace" -> doReturn("other").when(target).targetNamespace(); - case "private-scope" -> doReturn("ISOLATED").when(target).playableStateScope(); - case "created-policy" -> doReturn("PLAYER_CREATED").when(target).characterCreationPolicy(); - case "durable-abort" -> doReturn(true).when(target).positiveDurableAbort(); - default -> {} - } - var login = loginCustody(); - var expiry = "expired-login".equals(change) ? NOW.plusSeconds(90) : DIRECT_SCOPE_EXPIRY; - var scope = directTextScope(target, login, expiry); - var original = - switch (change) { - case "original-request" -> - new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), LOGIN_CONTEXT, 1); - case "original-context" -> - new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, UUID.randomUUID(), 1); - case "attempt-fence" -> - new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, LOGIN_CONTEXT, 2); - default -> ORIGINAL; - }; - var transport = - switch (change) { - case "transport-session" -> - new ObservedDirectTextTransport("42", TRANSPORT.proxyConnectionId()); - case "transport-proxy" -> new ObservedDirectTextTransport("00042", UUID.randomUUID()); - default -> TRANSPORT; - }; - var checks = new AtomicInteger(); - BooleanSupplier current = - switch (change) { - case "stale-custody" -> () -> false; - case "throwing-custody" -> - () -> { - throw new IllegalStateException("Controlled custody lost"); - }; - case "null-custody" -> null; - case "custody-lost-before-rpc" -> () -> checks.incrementAndGet() < 3; - default -> () -> true; - }; - if ("closed-login".equals(change)) { - when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Controlled closed LOGIN")); - } - Clock clientClock = - switch (change) { - case "expired-login" -> Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC); - case "expired-scope" -> Clock.fixed(DIRECT_SCOPE_EXPIRY, ZoneOffset.UTC); - default -> CLOCK; - }; - UUID selectedReadId = "read-correlation".equals(change) ? new UUID(0, 0) : READ_REQUEST; - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Server server = - server("account", calls, observedJwt, observedPeer, context(), login.evidence()); - try (var client = client(server, clientClock)) { - client.init(); - assertThatThrownBy( - () -> client.read(scope, original, transport, selectedReadId, login, current)) - .isInstanceOf(RuntimeException.class); - assertThat(calls).hasValue(0); - assertThat(observedJwt).hasValue(null); - assertThat(observedPeer).hasValue(null); - } finally { - stop(server); - } - } - - @ParameterizedTest - @ValueSource(strings = {"wrong-service", "wrong-namespace"}) - void directTextWrongAccountPeerReceivesNoCredential(String identity) throws Exception { - var context = context(); - var login = loginCustody(); - var scope = directTextScope(context.resolvedTarget(), login, DIRECT_SCOPE_EXPIRY); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Server server = server(identity, calls, observedJwt, observedPeer, context, login.evidence()); - try (var client = client(server)) { - client.init(); - assertThatThrownBy( - () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true)) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - failure -> - assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); - assertThat(calls).hasValue(0); - assertThat(observedJwt).hasValue(null); - } finally { - stop(server); - } - } - - @ParameterizedTest - @ValueSource( - strings = { - "version", - "owner-proof", - "pointer-digest", - "scope-expiry", - "login-jti", - "login-hash", - "login-context" - }) - void directTextRejectsAuthenticatedResponseBindingDrift(String change) throws Exception { - var target = context().resolvedTarget(); - var login = loginCustody(); - var scope = directTextScope(target, login, DIRECT_SCOPE_EXPIRY); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - BiConsumer, Map> drift = - (value, sources) -> { - switch (change) { - case "version" -> value.put("canonicalVersionId", UUID.randomUUID().toString()); - case "owner-proof" -> - sources.put("gameSessionOwnerProofDigest", "sha256:" + "9".repeat(64)); - case "pointer-digest" -> sources.put("admissionPointerSnapshotDigest", "9".repeat(64)); - case "scope-expiry" -> - value.put("connectScopeExpiresAt", DIRECT_SCOPE_EXPIRY.plusSeconds(1).toString()); - case "login-jti" -> sources.put("callerTokenJti", UUID.randomUUID().toString()); - case "login-hash" -> sources.put("callerTokenSha256", "9".repeat(64)); - case "login-context" -> sources.put("callerContextId", UUID.randomUUID().toString()); - default -> throw new IllegalArgumentException(change); - } - }; - Server server = - server( - "account", - calls, - observedJwt, - observedPeer, - target, - DIRECT_SCOPE_EXPIRY, - login.evidence(), - drift, - () -> {}); - try (var client = client(server)) { - client.init(); - assertThatThrownBy( - () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true)) - .isInstanceOf(IllegalArgumentException.class); - assertThat(calls).hasValue(1); - assertThat(observedJwt).hasValue(JWT); - } finally { - stop(server); - } - } - - @ParameterizedTest - @ValueSource(strings = {"custody", "scope-expiry", "login-expiry", "closed-login"}) - void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { - var target = context().resolvedTarget(); - var login = loginCustody(); - var expiry = "login-expiry".equals(change) ? NOW.plusSeconds(90) : DIRECT_SCOPE_EXPIRY; - var scope = directTextScope(target, login, expiry); - var current = new AtomicBoolean(true); - var clockTime = new AtomicReference<>(NOW); - Clock movingClock = mock(Clock.class); - when(movingClock.instant()).thenAnswer(invocation -> clockTime.get()); - var calls = new AtomicInteger(); - var observedJwt = new AtomicReference(); - var observedPeer = new AtomicReference(); - Runnable afterRead = - () -> { - switch (change) { - case "custody" -> current.set(false); - case "scope-expiry" -> clockTime.set(DIRECT_SCOPE_EXPIRY); - case "login-expiry" -> clockTime.set(NOW.plusSeconds(60)); - case "closed-login" -> - when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Closed LOGIN")); - default -> throw new IllegalArgumentException(change); - } - }; - Server server = - server( - "account", - calls, - observedJwt, - observedPeer, - target, - expiry, - login.evidence(), - (value, sources) -> {}, - afterRead); - try (var client = client(server, movingClock)) { - client.init(); - assertThatThrownBy( - () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, current::get)) - .isInstanceOf(RuntimeException.class); - assertThat(calls).hasValue(1); - } finally { - stop(server); - } - } - - private static DirectTextAuthenticatedLobbyScope directTextScope( - CanonicalPlayableTarget target, CanonicalGameplayLoginResult login, Instant expiry) { - return new DirectTextAuthenticatedLobbyScope( - UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), - InitialGameplayLoginContextState.installed(ORIGINAL, login), - TRANSPORT, - target, - DirectTextIssuedConnectScope.fromAccountResponse( - FirstPartyReceivingFixture.ACCOUNT.toString(), - DirectTextAuthenticatedLobbyScope.targetFor(target), - IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("direct-text-owned-scope") - .setEvaluatedAt(NOW.minusSeconds(10).toString()) - .setConnectScopeExpiresAt(expiry.toString()) - .build(), - CLOCK)); - } - - private static AccountPlayerAdmissionEntitlementClient client(Server server) throws Exception { - return client(server, CLOCK); - } - - private static AccountPlayerAdmissionEntitlementClient client(Server server, Clock clock) - throws Exception { - var endpoints = new ServiceEndpointsProperties(); - endpoints.setAccountService("localhost:" + server.getPort()); - return new AccountPlayerAdmissionEntitlementClient( - endpoints, - pki.clientProperties(directory, pki.identity("client")), - new GrpcChannelFactory(), - NAMESPACE, - clock); - } - - private static Server server( - String identity, - AtomicInteger calls, - AtomicReference observedJwt, - AtomicReference observedPeer, - FirstPartyConnectContext context, - CanonicalGameplayLoginResult.NonSecretEvidence login) - throws Exception { - return server( - identity, - calls, - observedJwt, - observedPeer, - context.resolvedTarget(), - Instant.ofEpochMilli(context.claims().expiresAtMillis()), - login, - (value, sources) -> {}, - () -> {}); - } - - private static Server server( - String identity, - AtomicInteger calls, - AtomicReference observedJwt, - AtomicReference observedPeer, - CanonicalPlayableTarget target, - Instant scopeExpiry, - CanonicalGameplayLoginResult.NonSecretEvidence login, - BiConsumer, Map> drift, - Runnable afterRead) - throws Exception { - var service = - new AccountPlayerAdmissionEntitlementReadServiceGrpc - .AccountPlayerAdmissionEntitlementReadServiceImplBase() { - @Override - public void readPlayerAdmissionEntitlement( - ReadPlayerAdmissionEntitlementRequest request, - StreamObserver observer) { - calls.incrementAndGet(); - var peer = GrpcPeerIdentity.current(); - observedPeer.set(peer == null ? null : peer.uri()); - try { - var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(request); - observedJwt.set(presented.initialLoginJwt()); - var evidence = evidence(presented.request(), target, scopeExpiry, login, drift); - afterRead.run(); - observer.onNext( - RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( - presented.request(), evidence)); - observer.onCompleted(); - } catch (Exception malformed) { - observer.onError( - Status.INVALID_ARGUMENT - .withDescription("Controlled Account fixture rejected request") - .asRuntimeException()); - } - } - }; - var serverIdentity = pki.identity(identity); - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forServer( - serverIdentity.privateKey(), serverIdentity.certificate())) - .trustManager(pki.caCertificate()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) - .build() - .start(); - } - - private static void stop(Server server) throws InterruptedException { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - - private static FirstPartyConnectContext context() { - var fixture = new FirstPartyReceivingFixture(); - CanonicalPlayableTarget target = org.mockito.Mockito.spy(fixture.target()); - doReturn("PRESEEDED_ONLY").when(target).characterCreationPolicy(); - when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)).thenReturn(target); - return fixture.service.parse(fixture.token()).orElseThrow(); - } - - private static CanonicalGameplayLoginResult loginCustody() throws Exception { - return loginCustody(new ArrayList<>()); - } - - private static CanonicalGameplayLoginResult loginCustody(List borrowed) throws Exception { - var login = mock(CanonicalGameplayLoginResult.class); - String jwtSha256 = - HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(JWT.getBytes(StandardCharsets.US_ASCII))); - var evidence = - new CanonicalGameplayLoginResult.NonSecretEvidence( - FirstPartyReceivingFixture.ACCOUNT, - LOGIN_REQUEST, - LOGIN_CONTEXT, - LOGIN_JTI, - jwtSha256, - GameSessionAccountDelegationProfile.PROFILE, - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(60).getEpochSecond(), - "1", - "1", - canonical(GameSessionAccountDelegationProfile.authorityTuple(1, 1)), - canonical( - List.of( - Map.of( - "outboxStreamKey", - "account:auth-authority:v1:account/" + FirstPartyReceivingFixture.ACCOUNT, - "outboxSequence", - "0"), - Map.of( - "outboxStreamKey", - "account:auth-authority:v1:issuer/firemud-account-service", - "outboxSequence", - "0"))), - canonical(List.of())); - when(login.evidence()).thenReturn(evidence); - when(login.compactJwtBytes()) - .thenAnswer( - invocation -> { - byte[] bytes = JWT.getBytes(StandardCharsets.US_ASCII); - borrowed.add(bytes); - return bytes; - }); - return login; - } - - private static ByteString canonical(Object value) throws Exception { - return ByteString.copyFrom( - Rfc8785CanonicalJson.canonicalizeUtf8( - tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value))); - } - - private static RuntimePlayerAdmissionEntitlementEvidence evidence( - RuntimePlayerAdmissionEntitlementGrpcCodec.Request request, - CanonicalPlayableTarget retained, - Instant scopeExpiry, - CanonicalGameplayLoginResult.NonSecretEvidence login, - BiConsumer, Map> drift) - throws Exception { - Instant scopeStarted = NOW.minusSeconds(10); - Map target = new LinkedHashMap<>(); - target.put("targetClass", "PUBLIC_PRODUCTION"); - target.put("characterCreationPolicy", "PRESEEDED_ONLY"); - target.put("targetNamespace", retained.targetNamespace()); - target.put("tenantId", retained.canonicalTenantId().toString()); - target.put("tenantSlug", retained.tenantSlug()); - target.put("worldSlug", retained.worldSlug()); - target.put("realmId", retained.realmId().toString()); - target.put("realmSlug", retained.realmSlug()); - target.put("playableStateNamespaceId", retained.playableStateNamespaceId().toString()); - target.put("playableStateScope", retained.playableStateScope()); - target.put("gameInstanceId", retained.canonicalGameInstanceId().toString()); - target.put("canonicalVersionId", retained.canonicalVersionId().toString()); - target.put("catalogRevision", Long.toString(retained.catalogRevision())); - target.put("pointerVersion", Long.toString(retained.pointerVersion())); - target.put("activeWorldEpoch", Long.toString(retained.activeWorldEpoch())); - target.put("evaluatedAt", scopeStarted.toString()); - target.put("connectScopeExpiresAt", scopeExpiry.toString()); - - Map facts = new LinkedHashMap<>(); - facts.put("sourceKind", "NON_PAID_DEMO"); - facts.put("subscriptionStatus", null); - facts.put("provisioningStatus", null); - for (String field : - List.of( - "gameplayAvailable", - "allowPublicJoin", - "allowNewGameplayBindings", - "allowNewInstanceStarts")) { - facts.put(field, true); - } - facts.put( - "quotas", - Map.of( - "maxActiveSessions", "3", - "maxConcurrentGameInstances", "2", - "maxStorageBytes", "4096")); - facts.put("entitlementVersion", "1"); - facts.put("tenantBillingSequence", "1"); - facts.put("tenantAuthorityGeneration", "2"); - - Map sources = new LinkedHashMap<>(); - sources.put("callerTokenJti", login.tokenJti().toString()); - sources.put("callerTokenSha256", login.tokenSha256()); - sources.put("callerRegistryRecordSha256", "a".repeat(64)); - sources.put("callerCommitProofSha256", "b".repeat(64)); - sources.put("callerContextId", login.callerContextId().toString()); - sources.put("callerOperationId", LOGIN_REQUEST.toString()); - sources.put( - "callerTokenExpiresAt", Instant.ofEpochSecond(login.expiresAtEpochSecond()).toString()); - sources.put("paidReceiptValidUntil", null); - sources.put("scopeDigest", "sha256:" + "c".repeat(64)); - sources.put("entitlementSourceDigest", "sha256:" + "d".repeat(64)); - sources.put("admissionPointerSnapshotDigest", retained.admissionPointerSnapshotDigest()); - sources.put("gameSessionOwnerProofDigest", retained.ownerProofDigest()); - sources.put("publishedPolicySetDigest", "sha256:" + "e".repeat(64)); - sources.put("worldLifecycleDigest", "sha256:" + "f".repeat(64)); - sources.put("worldCaptureId", "77777777-7777-4777-8777-777777777777"); - sources.put("worldRowVersion", "0"); - drift.accept(target, sources); - - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - request.target().readRequestId(), - request.expectedGameSessionWorkload(), - request.connectScopeId(), - membership(request.target().accountId(), request.target().tenantId(), retained), - target, - facts, - sources, - NOW); - } - - private static Snapshot membership(UUID account, UUID tenant, CanonicalPlayableTarget target) - throws Exception { - UUID sourceRequest = UUID.fromString("88888888-8888-4888-8888-888888888888"); - String hash = "a".repeat(64); - String requestDigest = - GameTenantCreationDigest.requestDigest( - target.targetNamespace(), sourceRequest, target.worldSlug(), "World", null); - var freshTenant = - new FreshTenantCreationEvidence( - 1, - target.targetNamespace(), - sourceRequest, - sourceRequest, - requestDigest, - tenant, - 17, - target.worldSlug(), - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - target.targetNamespace(), - sourceRequest, - sourceRequest, - requestDigest, - tenant, - 17, - target.worldSlug(), - "NEW_GAME_ROW")); - var authorityRequest = - new TenantAuthorityEventV1Codec.AuthorityRequest( - sourceRequest, - "sha256:" + hash, - tenant, - freshTenant.creationRequestId(), - freshTenant.requestDigest()); - var billing = - new TenantAuthorityEventV1Codec.BillingReceipt( - tenant, - sourceRequest, - "sha256:" + hash, - TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenant), - 1, - TenantAuthorityEventV1Codec.tenantBillingEventId(sourceRequest), - "sha256:" + hash); - var event = TenantAuthorityEventV1Codec.seal(authorityRequest, freshTenant, 2, 2, 1, billing); - String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; - var tuple = - new AuthorityTuple( - "1", - "1", - Map.of(tenant.toString(), "2"), - Map.of(tenant.toString(), "1"), - List.of(), - Optional.empty(), - Optional.of( - Map.of( - tenant.toString(), - new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); - return new Snapshot( - "firemud-account-service", - account.toString(), - tenant.toString(), - false, - "MISSING", - false, - Map.of(tenant.toString(), "1"), - "1", - List.of(), - tuple, - "1", - List.of( - new Checkpoint(prefix + "account/" + account, "0"), - new Checkpoint(prefix + "issuer/firemud-account-service", "0"), - new Checkpoint(prefix + "membership/" + account + "/" + tenant, "0"), - new Checkpoint(event.outboxStreamKey(), "1")), - List.of( - new SourceEvidence( - event.outboxStreamKey(), - "1", - event.eventId().toString(), - event.eventDigest(), - new String(event.payload(), StandardCharsets.UTF_8)))); - } -} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 7f4e0d1c26..448b954fd5 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -305,9 +305,7 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @Container static final PostgreSQLContainer ACCOUNT = - // Account's exact-original LOGIN disposal refuses nondurable PostgreSQL settings. - new PostgreSQLContainer<>(TestContainerImages.postgres()) - .withCommand("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer REDIS = @@ -586,9 +584,6 @@ private void compose( "Created placement proof requires the committed coupled owner path"); } UUID tenant = UUID.randomUUID(); - var sharedAuthoredSource = controlledSource("controlled-upstream", tenant); - var sharedCreation = - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sharedAuthoredSource); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT.getJdbcUrl(), @@ -597,22 +592,13 @@ private void compose( REDIS.getHost(), REDIS.getMappedPort(6379), proofDirectory.resolve("account"), - sharedCreation, + tenant, true); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( account, proofDirectory.resolve("issuer"), NAMESPACE); - var accountDurability = - issuer - .sourceDsl() - .fetchSingle( - "SELECT pg_is_in_recovery() AS recovery, current_setting('fsync') AS fsync," - + " current_setting('synchronous_commit') AS commit_mode"); - assertThat(accountDurability.get("recovery", Boolean.class)).isFalse(); - assertThat(accountDurability.get("fsync", String.class)).isEqualTo("on"); - assertThat(accountDurability.get("commit_mode", String.class)).isEqualTo("on"); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) @@ -696,14 +682,7 @@ public void attachAccountRedemptionProjection( var createdPublication = new AtomicReference(); var preparedInput = preparationInputs( - world, - gs, - tuple, - claim.get(), - tenant, - playerCreatedPlacement, - createdPublication, - sharedAuthoredSource); + world, gs, tuple, claim.get(), tenant, playerCreatedPlacement, createdPublication); var input = refusal == Refusal.MISMATCHED_ATTEMPT ? new WorldCanonicalInstancePreparation.Input( @@ -1881,7 +1860,6 @@ public void close() {} exerciseCoupledCanonicalInitialAdmission( gs, world, - account, issuer, currentAttempt, proofDirectory, @@ -2448,7 +2426,6 @@ private static String prefixedSha256(byte[] bytes) { private static void exerciseCoupledCanonicalInitialAdmission( Database gs, Database world, - AccountControlUiOriginalOrderFixture account, AccountOriginalStartSessionAuthorizationProofFixture issuer, GrpcOriginalStartSessionCurrentAttemptClient currentAttempt, Path proofDirectory, @@ -3031,7 +3008,6 @@ private static void exerciseCoupledCanonicalInitialAdmission( composeActualEntityWorldRegionPrerequisite( gs, world, - account, proofDirectory, pki, factory, @@ -3112,7 +3088,6 @@ private static void assertAccountAdmissionProtectionSettled( private static void composeActualEntityWorldRegionPrerequisite( Database gs, Database world, - AccountControlUiOriginalOrderFixture account, Path proofDirectory, WorldOriginalStartSessionPreparationProofPki worldPki, GrpcChannelFactory channels, @@ -3461,8 +3436,6 @@ private static void composeActualEntityWorldRegionPrerequisite( try { var worldEndpoints = new ServiceEndpointsProperties(); worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); - // The earlier generic password-write proof deliberately leaves creator LOGIN - // currentness unavailable. The later composition uses a separate fresh player. var initialLocationClient = new CanonicalInitialPlayerLocationClient( worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); @@ -3569,18 +3542,6 @@ private static void composeActualEntityWorldRegionPrerequisite( assertThat(regionProofs.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); assertThat(regionProofs.expiredGrantRejectedWithoutStateChange()).isTrue(); } - // Run the genuine second-player DEMO mutation after original placement assertions. - WorldPublishedAdmissionSourceComposition.exercise( - proofDirectory, - gs.dsl(), - gs.manager(), - REDIS.getHost(), - REDIS.getMappedPort(6379), - currentTarget, - accountUuid, - account, - worldEndpoints, - worldPki.client("game-session-service")); } finally { shutdown(worldLocationServer); entityReceiptClient.close(); @@ -4200,11 +4161,11 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, UUID tenant, boolean playerCreatedPlacement, - AtomicReference createdPublication, - AuthoredWorldSourceEvidence source) + AtomicReference createdPublication) throws Exception { var intakeRepository = new WorldAuthoredSourceIntakeRepository(world.dsl()); var versionRepository = new WorldAuthoredVersionIdentityRepository(world.dsl()); + var source = controlledSource("controlled-upstream", tenant); var intake = Objects.requireNonNull( world diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java deleted file mode 100644 index 93461ec33c..0000000000 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ /dev/null @@ -1,250 +0,0 @@ -package net.firedevops.firemud.worldmanagement.tenant; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import java.net.InetSocketAddress; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Clock; -import java.time.Duration; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; -import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; -import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; -import net.firedevops.firemud.accountservice.service.session.AccountPlayerAdmissionSharedEntitlementFixture; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; -import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; -import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; -import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; -import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginPhysicalCompositionFixture; -import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; - -/** - * Actual LOGIN and PLAYER_ADMISSION producer/consumer with a genuine absent player and shared - * Account/GS/World sources and physical GS journal/PENDING/INSTALLED state, followed by actual - * first JOIN, positive source read and known-token retirement. DEMO policy, caller coordinates, - * PKI, reset/promotion qualification and receiving custody remain controlled. No public ingress, - * protected receiving custody, World hold across JOIN, runtime activation or PLAY is proved. - */ -final class WorldPlayerAdmissionEntitlementComposition { - private WorldPlayerAdmissionEntitlementComposition() {} - - static void exercise( - Path root, - AccountControlUiOriginalOrderFixture original, - CanonicalGameplayAdmissionDecisionReadClient targets, - CanonicalPlayableTarget target, - org.jooq.DSLContext gs, - org.springframework.transaction.PlatformTransactionManager gsTransactions, - String redisHost, - int redisPort) - throws Exception { - var clock = Clock.systemUTC(); - String namespace = target.targetNamespace(); - Path directory = Files.createDirectories(root.resolve("player-admission")); - var pki = - LoopbackMtlsTestPki.create( - directory, - "Controlled genuine player admission sources", - new LoopbackMtlsTestPki.IdentitySpec( - "gs", "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", false), - new LoopbackMtlsTestPki.IdentitySpec( - "account", "spiffe://firemud/ns/" + namespace + "/sa/account-service", true)); - var creation = original.creationEvidence(); - var demo = - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - creation.canonicalTenantId(), - creation.creationRequestId(), - creation.requestDigest(), - null, - null, - null, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)); - var fixture = - new AccountPlayerAdmissionSharedEntitlementFixture( - original, directory, targets, demo, clock); - var loginOwner = fixture.login(); - var keys = pki.keyManagerFactory(pki.identity("account")); - var trust = pki.trustManagerFactory(); - Server loginServer = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer(keys)) - .trustManager(trust) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService( - ServerInterceptors.intercept( - loginOwner.authenticateReceiver(namespace), new GrpcPeerIdentityInterceptor())) - .build() - .start(); - try { - Server entitlementServer = - fixture.receiver().createUnregisteredServer("127.0.0.1:0", keys, trust); - entitlementServer.start(); - try { - var loginEndpoints = new ServiceEndpointsProperties(); - loginEndpoints.setAccountService("localhost:" + loginServer.getPort()); - var entitlementEndpoints = new ServiceEndpointsProperties(); - entitlementEndpoints.setAccountService("localhost:" + entitlementServer.getPort()); - var tls = pki.clientProperties(directory, pki.identity("gs")); - var channels = new GrpcChannelFactory(); - var source = fixture.trustedJwksSource(); - var verifier = - new AccountAsymmetricJwtVerifier( - new AccountPublicJwksCache( - source, source.sourceIdentity(), clock, Duration.ofSeconds(30)), - clock); - try (var loginClient = - new CanonicalGameplayLoginAccountClient( - loginEndpoints, - tls, - channels, - BlockingGrpcStubCustomizer.noop(), - namespace, - clock, - Duration.ofSeconds(15), - verifier); - var entitlementClient = - new AccountPlayerAdmissionEntitlementClient( - entitlementEndpoints, tls, channels, namespace, clock)) { - loginClient.initialize(); - entitlementClient.init(); - // This request is only a controlled credential source. GS allocates real coordinates. - var credentialSource = - loginOwner.loginRequest( - UUID.randomUUID(), - new GameplayCredentialSourceContext( - UUID.randomUUID(), "192.0.2.42", "trusted_tcp_proxy")); - try (var physicalLogin = - InitialGameplayLoginPhysicalCompositionFixture.open( - gs, - gsTransactions, - redisHost, - redisPort, - loginClient, - credentialSource.email(), - "192.0.2.42", - credentialSource.credential().toCharArray())) { - var login = physicalLogin.loginResult(); - var evidence = login.evidence(); - loginOwner.assertCommittedNonAdmittingLogin( - evidence.requestId(), - evidence.callerContextId(), - evidence.tokenJti(), - evidence.tokenSha256(), - evidence.expiresAtEpochSecond()); - var transport = new ObservedDirectTextTransport("1", UUID.randomUUID()); - var realmScope = - fixture.issueScopeWithControlledGameSessionCaller( - new DirectTextCallerContext( - evidence.accountId(), - target.canonicalTenantId(), - target.realmId(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - transport.proxyConnectionId().toString(), - UUID.randomUUID().toString()), - new DirectTextJoinTarget( - target.canonicalTenantId(), - target.realmId(), - target.worldSlug(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion())); - var scope = realmScope.scope(); - var issued = - DirectTextIssuedConnectScope.fromAccountResponse( - evidence.accountId().toString(), - DirectTextAuthenticatedLobbyScope.targetFor(target), - IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId(scope.connectScopeId()) - .setEvaluatedAt(scope.evaluatedAt()) - .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) - .build(), - clock); - var coordinates = physicalLogin.coordinates(); - // Physical INSTALLED readback is real; protected receiving custody remains controlled. - var lobby = - new DirectTextAuthenticatedLobbyScope( - UUID.randomUUID(), - physicalLogin.installedReadback(), - transport, - target, - issued); - var received = - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); - fixture.assertNonAdmittingEvidence(received); - assertThat(received.fields()).containsEntry("variant", "PLAYER_ADMISSION"); - // Actual Account owner transition; caller binding is controlled and no World hold - // spans this JOIN transaction. Reuse only the still-current verified LOGIN result. - fixture.commitFirstJoin( - realmScope, UUID.randomUUID().toString(), transport.proxyConnectionId().toString()); - var joined = - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); - fixture.assertAdmittingEvidence(joined); - assertThatThrownBy( - () -> - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) - .isInstanceOf(RuntimeException.class); - assertThat(physicalLogin.abandonOriginalAfterCustodyLoss().status()) - .isEqualTo( - net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner - .Status.ACCOUNT_RETIRED); - assertThatThrownBy( - () -> - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) - .isInstanceOf(RuntimeException.class); - } catch (RuntimeException | Error failure) { - failure.addSuppressed( - new AssertionError( - "Account LOGIN owner stages: " + loginOwner.ownerObservations())); - throw failure; - } - } - } finally { - stop(entitlementServer); - } - } finally { - stop(loginServer); - } - } - - private static void stop(Server server) throws InterruptedException { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } -} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java deleted file mode 100644 index a1e9ed5ffb..0000000000 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ /dev/null @@ -1,247 +0,0 @@ -package net.firedevops.firemud.worldmanagement.tenant; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.grpc.BindableService; -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import io.grpc.stub.StreamObserver; -import java.net.InetSocketAddress; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; -import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; -import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; -import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; -import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.repository.CanonicalPublishedAdmissionActualOwnerCompositionFixture; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; -import org.jooq.DSLContext; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Real GS OPEN/current publication and World ACTIVE reads over authenticated sockets, followed by - * actual Account LOGIN, absent-player entitlement, owner-local first JOIN and positive source - * reread. Game Design publication, DEMO policy, PKI, caller coordinates and custody callbacks are - * controlled. No public ingress, World hold across JOIN, protected receiving custody or activation - * is proved. - */ -final class WorldPublishedAdmissionSourceComposition { - private WorldPublishedAdmissionSourceComposition() {} - - static void exercise( - Path root, - DSLContext gs, - org.springframework.transaction.PlatformTransactionManager gsTransactions, - String redisHost, - int redisPort, - CanonicalPlayableTarget target, - UUID account, - net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture - originalAccount, - ServiceEndpointsProperties worldEndpoints, - CommonGrpcClientProperties worldTls) - throws Exception { - assertThat(target.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); - var publication = - RealmPolicyPublishedEvidenceCodec.decode( - gs.fetchSingle( - "SELECT complete_policy_set_evidence FROM game_session_canonical_realm_catalog WHERE realm_id=?", - target.realmId()) - .get(0, byte[].class)); - String namespace = target.targetNamespace(); - Path directory = Files.createDirectories(root.resolve("published-admission-source")); - var pki = - LoopbackMtlsTestPki.create( - directory, - "Controlled published source composition", - new LoopbackMtlsTestPki.IdentitySpec( - "gs-server", peer(namespace, "game-session-service"), true), - new LoopbackMtlsTestPki.IdentitySpec( - "gs-client", peer(namespace, "game-session-service"), false), - new LoopbackMtlsTestPki.IdentitySpec( - "account", peer(namespace, "account-service"), false), - new LoopbackMtlsTestPki.IdentitySpec( - "design", peer(namespace, "game-design-service"), true)); - var policies = - new PublishedRealmEntryPolicySetEvidence( - publication.target(), - publication.versionNumber(), - publication.sourceCommitId(), - publication.sourceEpoch(), - publication.publishedReleaseBundleRef(), - publication.publishedReleaseBundleDigest(), - publication.publishWorkflowId(), - publication.manifestHash(), - publication.publicationVersionStateEpoch(), - publication.operationBytes(), - publication.captureBytes(), - publication.terminalEvidenceBytes(), - publication.policyCount(), - publication.policySetDigest(), - publication.policies().stream() - .map( - p -> - new PublishedRealmEntryPolicyEvidence( - p.policyId(), - p.source().commitId(), - p.source().revisionId(), - p.source().logicalRevisionId(), - p.source().policy(), - p.policyDigest())) - .toList()); - // This is the sole stipulated source: the exact published set already used by the real - // preparation/OPEN owners. No Game Design issuing-owner proof is claimed here. - var policySource = - new PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase() { - @Override - public void listPublishedRealmEntryPolicies( - ListPublishedRealmEntryPoliciesRequest request, - StreamObserver observer) { - assertThat(GrpcPeerIdentity.current().uri()) - .isEqualTo(peer(namespace, "game-session-service")); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - observer.onNext( - PublishedRealmEntryPolicyReadGrpcCodec.toResponse( - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(request), policies)); - observer.onCompleted(); - } - }; - Server design = server(pki, "design", policySource); - try { - var endpoints = new ServiceEndpointsProperties(); - endpoints.setGameDesignService("localhost:" + design.getPort()); - var channels = new GrpcChannelFactory(); - try (var policyClient = - new GameDesignPublishedRealmPolicyClient( - endpoints, - pki.clientProperties(directory, pki.identity("gs-client")), - channels, - namespace); - var worldClient = - new WorldCanonicalInstanceLifecycleClient( - worldEndpoints, worldTls, channels, namespace)) { - policyClient.init(); - worldClient.init(); - Server receiver = - server( - pki, - "gs-server", - CanonicalPublishedAdmissionActualOwnerCompositionFixture.receiver( - gs, namespace, policyClient, worldClient)); - try { - endpoints.setGameSessionService("localhost:" + receiver.getPort()); - try (var accountClient = - new CanonicalGameplayAdmissionDecisionReadClient( - endpoints, - pki.clientProperties(directory, pki.identity("account")), - channels, - namespace)) { - accountClient.init(); - var selector = - new RetainedTargetSelector( - UUID.randomUUID(), - account, - namespace, - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion()); - var resolved = accountClient.resolvePublishedRealmAdmissionTarget(selector); - var read = accountClient.readPublishedRealmAdmissionOwner(resolved.strictSelector()); - assertThat(read.selector()).isEqualTo(resolved.strictSelector()); - assertThat(read.currentTarget().canonicalGameInstanceId()) - .isEqualTo(target.canonicalGameInstanceId()); - assertThat(read.sourceEvidence().admissionPointerSnapshotDigest()) - .isEqualTo(target.admissionPointerSnapshotDigest()); - assertThat(read.sourceEvidence().gameSessionOwnerProof().proofDigest()) - .isEqualTo(target.ownerProofDigest()); - assertThat(read.sourceEvidence().publishedPolicySetEvidence().canonicalBytes()) - .containsExactly(policies.canonicalBytes()); - assertThat(read.worldLifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); - assertThat(read.worldLifecycleEvidence().lifecycleEpoch()) - .isEqualTo(target.activeWorldEpoch()); - var wrong = - new RetainedTargetSelector( - UUID.randomUUID(), - account, - namespace, - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - UUID.randomUUID(), - target.catalogRevision(), - target.pointerVersion()); - assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) - .isInstanceOf(RuntimeException.class); - WorldPlayerAdmissionEntitlementComposition.exercise( - root, - originalAccount, - accountClient, - target, - gs, - gsTransactions, - redisHost, - redisPort); - } - } finally { - stop(receiver); - } - } - } finally { - stop(design); - } - } - - private static String peer(String namespace, String service) { - return "spiffe://firemud/ns/" + namespace + "/sa/" + service; - } - - private static Server server( - LoopbackMtlsTestPki.Pki pki, String identity, BindableService receiver) throws Exception { - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( - pki.keyManagerFactory(pki.identity(identity)))) - .trustManager(pki.trustManagerFactory()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) - .build() - .start(); - } - - private static void stop(Server server) throws InterruptedException { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } -} From 12901ed220dd41a224b8d733ae1e96ce70ad0e13 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 11:27:23 +1300 Subject: [PATCH 18/66] Keep existing capability evidence anchor repository-local --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 77f693dbd8..0ff14ff500 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -557,7 +557,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.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` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `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) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [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); [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); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [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); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `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); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_UNAVAILABLE` before entitlement reads, cached replay or token issuance; older positive-issuance tests are historical. 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 shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [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); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.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 [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | From 703523fc1d3a43fdb549bfc3711897a60d0a5087 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 11:02:12 +1300 Subject: [PATCH 19/66] Fix Account cutover review findings and exact temporary PLAY classification --- .github/scripts/classify-change-scope.cjs | 14 +- .../scripts/classify-change-scope.test.cjs | 23 ++ .../account-service/api-contracts.md | 16 +- .../account-service/runtime-and-data.md | 16 +- design/project-management/ai-observations.md | 4 +- .../player-access-and-session.md | 12 +- dev-tools/smoke/smoke_common.py | 12 +- .../pr-required-gate-context-contract.sh | 5 +- dev-tools/tests/smoke-transport-contract.sh | 34 ++- ...ostingSubscriptionLifecycleRepository.java | 80 ++++++- .../AccountSubscriptionIntentRepository.java | 21 +- ...CanonicalFirstJoinTerminalCoordinator.java | 11 +- ...ostingSubscriptionProvisioningService.java | 25 ++- .../service/impl/AccountServiceImpl.java | 10 +- .../AccountApplicationIntegrationTest.java | 1 + ...rUuidEntityCompositionIntegrationTest.java | 1 + ...iptionDispatchPostgresIntegrationTest.java | 204 ++++++++++++++++++ ...anonicalFirstJoinEventIntegrationTest.java | 74 ++++++- ...nicalFirstJoinPostgresIntegrationTest.java | 2 +- ...titlementOwnerPostgresIntegrationTest.java | 1 - ...AuthenticationPostgresIntegrationTest.java | 4 +- ...ionCompositionPostgresIntegrationTest.java | 2 +- ...ngSubscriptionLifecycleRepositoryTest.java | 37 +++- ...nicalFirstJoinTerminalCoordinatorTest.java | 54 +++++ ...untCanonicalPublicRealmScopeOwnerTest.java | 10 +- ...ngSubscriptionProvisioningServiceTest.java | 45 ++++ ...thorityEventProducerCanonicalJoinTest.java | 7 +- .../service/impl/AccountServiceImplTest.java | 77 +++++++ ...untRuntimeStubServerCompatibilityTest.java | 63 +++++- .../test/AccountRuntimeStubServer.java | 17 +- .../gamesession/client/AccountClientTest.java | 15 ++ 31 files changed, 817 insertions(+), 80 deletions(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index f18905e400..dff29ad5c8 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -133,6 +133,7 @@ function isPythonDependency(file) { function isLightweightEligible(file) { return ( (isDocumentation(file) || isValidationPython(file)) && + !isServiceSourceMarkdown(file) && file !== "dev-tools/docs/generate-erd.sh" && !isRuntimeAuthority(file) && !SHARED_FILES.has(file) @@ -157,16 +158,23 @@ function moduleForFile(file) { return null; } +function isServiceSourceMarkdown(file) { + return file.startsWith("services/") && + moduleForFile(file) !== null && + /^services\/[^/]+\/src\/.*\.md$/.test(file); +} + function classifyChangeScope(inputFiles, options = {}) { const files = [...new Set(inputFiles)].sort(); const forceAll = options.forceAll === true; - // Known service documentation retains docs proof without selecting runtime modules. - // Unknown service paths and every non-documentation input remain fail closed. + // Known service documentation outside source sets retains docs proof without + // selecting runtime modules, including README files under shared common-* paths. + // Unknown services, source resources and non-lightweight inputs remain fail closed. const moduleInputFiles = files.filter( (file) => !(file.startsWith("services/") && moduleForFile(file) !== null && - isDocumentation(file) && + !isServiceSourceMarkdown(file) && isLightweightEligible(file)), ); const runAll = diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 1b99e51091..320a8eabff 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -56,6 +56,29 @@ test("known service and shared-module documentation selects no heavy module proo } }); +test("Markdown packaged under known service source retains module proof", () => { + for (const [path, module, service] of [ + ["services/account-service/src/main/resources/content/README.md", "account-service", "account-service"], + ["services/account-service/src/test/resources/fixtures/README.md", "account-service", "account-service"], + ]) { + const result = classifyChangeScope([path]); + + assert.equal(result.runAll, false, path); + assert.equal(result.lightweightOnly, false, path); + assert.equal(result.docsChanged, true, path); + assert.deepEqual(result.affectedModules, [module], path); + assert.deepEqual(result.affectedServices, service ? [service] : [], path); + assert.deepEqual(result.bootableModules, service ? [service] : [], path); + } + + const sharedPath = "services/common-platform-core/src/main/resources/schema/README.md"; + const sharedResult = classifyChangeScope([sharedPath]); + assert.equal(sharedResult.runAll, true, sharedPath); + assert.equal(sharedResult.lightweightOnly, false, sharedPath); + assert.equal(sharedResult.docsChanged, true, sharedPath); + assert.deepEqual(sharedResult.affectedModules, ALL_MODULES, sharedPath); +}); + test("service documentation does not add modules to a cumulative runtime diff", async () => { const result = await classifyGithubFiles([ "services/common-platform-core/README.md", diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 578e13c10b..c8649584ab 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -141,7 +141,7 @@ Account UUID generation currently has three established provenances: `ACCOUNT_RE This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. -Current explicit JOIN status: Account's `JoinPublicProductionMembership` receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation. The Gateway route remains blocked by its guard and absent from `publicOpenAPI`. The held boundary, preserved positive obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); target JOIN authority and commit requirements remain in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). +Current explicit JOIN status: with the default composition absent, Account's `JoinPublicProductionMembership` service method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, the service method proceeds into scope/target validation and authority reads; the gRPC adapter can still refuse peer or request-shape failures before the service call. This does not establish default runtime exposure or qualified live JOIN. The Gateway route remains blocked by its guard and absent from `publicOpenAPI`. The held boundary, preserved positive obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); target JOIN authority and commit requirements remain in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). `ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. @@ -151,7 +151,7 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Current `JoinPublicProductionMembership` receiving returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap or scope validation, replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. 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 obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain 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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call. The Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. With canonical scope consumers absent, current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When consumers are manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/grant/pointer reads, token minting, or replay/session mutation. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. 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 obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Account UUID Response and REST Selector Identity @@ -223,7 +223,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `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. -- `IssueDirectTextConnectScope` – prepared internal Account API; the current receiving method returns `AUTH_UNAVAILABLE` before caller/scope, target, entitlement, or scope-persistence work. Game Session text `REALMS` dispatch remains pending under #2898. Current held status, preserved source obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); the target scope and transport contract remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +- `IssueDirectTextConnectScope` – prepared internal Account API; with the default scope producer absent, the receiving method returns `AUTH_UNAVAILABLE`. When manually configured, it delegates to the scope owner for caller/target validation and scope issuance. Game Session text `REALMS` dispatch remains pending under #2898. Current held status, preserved source obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); the target scope and transport contract remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). @@ -371,7 +371,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. Account's local creation protection covers the current authenticated player's membership, applicable realm grant, and entitlement authority; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection) for the cross-owner terminal boundary. | -| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** The local Account `JoinPublicProductionMembership` RPC implements explicit public-production membership creation; Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | +| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** A prepared Account `JoinPublicProductionMembership` component implements explicit public-production membership creation. With the default composition absent, the service method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable; when manually configured, it proceeds into validation and authority reads, while the gRPC adapter may refuse peer or request-shape failures before the service call. Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | | `POST` | `/tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | **Target-state only; not currently routable.** Target duplicate-safe create-or-extend surface. The body carries the exact `accountId`, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision` (absent-grant precondition for `CREATE`, required current revision for `EXTEND`); exact `mutationDigest/v1` retries replay the stored outcome and changed intent or revision returns `IDEMPOTENCY_CONFLICT` or `GRANT_REVISION_CONFLICT` as defined above. | @@ -382,8 +382,8 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** `accountId` is the canonical lowercase non-nil Account UUID. Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route remains implementation drift and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** Account returns `AUTH_UNAVAILABLE` before bootstrap or connect-scope validation, cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation; the held boundary and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** The current Account receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the Gateway path remains blocked by its explicit route guard. Current status, preserved obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current default composition:** absent canonical scope consumers, Account returns `AUTH_UNAVAILABLE` before bootstrap or connect-scope validation. With consumers manually configured, `issueConnectToken` validates the bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation; the held boundary and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** With the default composition absent, the current Account receiving method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. The Gateway path remains blocked by its explicit route guard. Current status, preserved obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -398,7 +398,7 @@ The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountI 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. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. **Current endpoint behavior:** after validating bootstrap identity and connect-scope binding, Account returns `AUTH_UNAVAILABLE` before cached-success replay or fresh membership, entitlement, and runtime authority reads, token minting, or replay/session mutation. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; no gRPC `IssueConnectToken` transport exists. +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. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. **Current default composition:** with canonical scope consumers absent, Account returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When manually configured, `issueConnectToken` validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, token minting, or replay/session mutation. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; 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. @@ -432,7 +432,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/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | 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 ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. The Account world/realm/character discovery, direct-scope, JOIN, and connect-token receiving methods currently return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, membership/entitlement/admission-pointer or cached-result reads, or token minting. 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. Target success delivery uses only 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. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | +| 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 ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. With default compositions absent, the Account world/realm/character discovery, direct-scope, JOIN, and connect-token receivers fail closed with `AUTH_UNAVAILABLE`; manually configured direct-scope and JOIN owners proceed into their applicable validation and authority reads, while configured connect-token validates bootstrap identity and reads the connect scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. With canonical scope consumers absent, current `POST /auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before membership/entitlement/admission-pointer or cached-result reads, or token minting. 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. Target success delivery uses only 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. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | 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. | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b2de36b601..679ee5b2ff 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -66,11 +66,11 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. The current `JoinPublicProductionMembership` receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutations. The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; the gRPC adapter can refuse peer or request-shape failures before the service call. The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` 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 Account public bootstrap discovery, direct-scope, JOIN, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the current receiving facade returns `AUTH_UNAVAILABLE` before reaching it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `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 numeric runtime entitlement endpoint returns retryable `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` 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 `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` 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. With the default composition absent, current public bootstrap discovery, direct-scope, JOIN, and connect-token receivers return `AUTH_UNAVAILABLE` before applicable validation or authority reads. When manually configured, direct-scope and JOIN proceed into their owner/consumer validation, and connect-token validates bootstrap identity and reads scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the current receiving facade returns `AUTH_UNAVAILABLE` before reaching it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `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 numeric runtime entitlement endpoint returns retryable `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` 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` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -261,12 +261,12 @@ Runtime caller contract: - Target success delivery uses only `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is not returned in the response body or a response-header fallback. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before creating a token or cookie, so no current first-party WebSocket admission is established. Under the target flow, browser/mobile clients and first-party non-browser clients with a protected cookie jar remain cookie-only. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. -- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. The Account `IssueDirectTextConnectScope` RPC is implemented locally: it receives trusted caller context and the exact Game Session-resolved target, validates the current catalog/pointer snapshot, and returns the opaque scope to Game Session. Game Session wiring from text `REALMS` and transport-local scope retention remain unimplemented, as does the subsequent text `JOIN` dispatch (#2898); the end-to-end producer flow and proof remain incomplete. +- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. A prepared Account `IssueDirectTextConnectScope` component can receive trusted caller context and the exact Game Session-resolved target, validate the current catalog/pointer snapshot, and return an opaque scope. With the default scope producer absent, the receiving method returns `AUTH_UNAVAILABLE`; when manually configured, it delegates to the scope owner for caller/target validation and scope issuance. This is not default runtime exposure or end-to-end proof. Game Session wiring from text `REALMS`, transport-local scope retention, and subsequent text `JOIN` dispatch (#2898) remain unimplemented; the end-to-end producer flow and proof remain incomplete. - `connectScopeExpiresAt` bounds how long the discovery-issued selector may be reused as a convenience token. Once it expires, callers must rerun discovery instead of treating the selector as a durable realm handle. - Account Service must expose bootstrap-discovery endpoints that accept only the `player-bootstrap` token profile and return the canonical caller-visible worlds, realms, characters, and a canonical `connectScopeId` selector for each admissible realm target. - Account Service must use the authoritative realm-routing contract when issuing `/auth/connect-token` so connect-token scope is pinned to the tenant's current admissible instance for the selected realm instead of a caller-supplied guess. - `requestId` is the idempotency key for connect-token issuance. Retrying the same `(accountId, connectScopeId, requestId)` replays the same deterministic application failure directly while its retained failure envelope is available. A stored success returns the same token payload only after current authority and all applicable admission, registry, and issuance postconditions revalidate; failed revalidation returns the applicable canonical denial without reminting or mutating the committed issuance result. If the compact receipt still exists after its encrypted response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`, never remints or reconstructs a JWT, and is terminal for that original issuance attempt; callers must start a fresh authorized request under a new `requestId`. A changed digest remains `IDEMPOTENCY_CONFLICT`. The exact membership freshness baseline used for issuance is bound to that `connectScopeId` and `requestId`; it is immutable comparison evidence, not a duplicate request field. If Gateway may already have consumed the token, the caller must rediscover and use a new `requestId` rather than replaying the prior issuance key. - - **Target contract; current Account behavior is fail-closed.** The target requires caller-bound membership for every selected target. For a publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. **Current runtime:** `AccountServiceImpl.issueConnectToken` validates the bootstrap identity and connect scope, then returns `AUTH_UNAVAILABLE` before membership checks, replay reads or writes, token minting, or session mutation. A private or playtest target additionally requires the current Account-owned realm-access grant under the target contract; a grant never substitutes for membership or public onboarding. The canonical contracts remain in [Authentication](../../system-architecture-authentication.md) and [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). + - **Target contract; current Account behavior is fail-closed.** The target requires caller-bound membership for every selected target. For a publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. **Current receiving boundary:** `AccountServiceImpl.issueConnectToken` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation or authority reads, so the prepared validation and issuance components are not exposed by this receiver. A private or playtest target additionally requires the current Account-owned realm-access grant under the target contract; a grant never substitutes for membership or public onboarding. The canonical contracts remain in [Authentication](../../system-architecture-authentication.md) and [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). - The target membership-writer contract is `JoinPublicProductionMembership`; its canonical caller, scope, policy, and replay behavior is owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Connect-token issuance and public-production `PLAY` require existing membership and never invoke the writer implicitly. The local Account RPC, digest, transaction, and recovery status are recorded under [Implementation Status](#implementation-status). - It is valid only for the default public production realm and only when the caller satisfies the public-production admission policy. @@ -316,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is being qualified in the canonical public receiving branch. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) owns receiving proof and gaps. +The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is being qualified in the canonical public receiving branch. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences @@ -353,11 +353,11 @@ Existing `AccountRealmAccessGrant` persistence and registered internal grant rea ### Runtime Implementation Status and Drift -- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. The current `JoinPublicProductionMembership` receiving facade returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, or entitlement reads or membership mutation; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. +- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- 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 public bootstrap discovery, direct-scope, JOIN, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The current Account JOIN receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the public Gateway route remains blocked by its explicit guard. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) for the held boundary and preserved component obligations/proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- 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. With the default composition absent, current public bootstrap discovery, direct-scope, JOIN, and connect-token receivers return `AUTH_UNAVAILABLE` before applicable validation or authority reads. When manually configured, direct-scope and JOIN proceed into their owner/consumer validation, and connect-token validates bootstrap identity and reads scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. With the default composition absent, the Account JOIN receiving method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; gRPC peer/shape checks can refuse before the service call; the public Gateway route remains blocked by its explicit guard. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) for the held boundary and preserved component obligations/proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. -The current JOIN implementation re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). +The prepared JOIN component re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. With the default composition absent, the JOIN receiver returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. This does not establish default runtime exposure or qualified live JOIN. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on the JOIN receipt and unknown-outcome reconciliation work in #2848. No universal retention duration is implied. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2171887f4a..75cb8eca99 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -33,7 +33,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-02` (Pacific/Auckland): SpotBugs crashed during Account authentication extraction. - A distinct local JVM failure occurred at 5:06:16am NZDT on 2 November during the 49-file Account authentication extraction: the Temurin 25.0.5+8 SpotBugs worker `2436948` crashed with `SIGSEGV` in `IndexSetIterator::advance_and_next` while C2 compiled `ValueRangeAnalysisFactory.analyze`. The wrapper returned exit 1 without an observed resource-drain stall. Root preserved the fatal and compiler-replay logs in R1430 and reported the occurrence to Overseer. This differs from the earlier Java 21 G1 daemon failure; a common cause is unproven. Next: retain the unchanged targeted SpotBugs retry outcome and compare exact JVM/frame evidence if it recurs; do not treat passing tests as completion of the failed static gate. - - Recurrence on 3 November: public receiving proof346 crashed Temurin 25.0.5+8 worker4180380 during `:common-platform-core:spotbugsTest` with `SIGSEGV` in `PhaseIdealLoop::build_loop_late`. Fatal and replay logs are retained privately in R1430/public-static346-jvm and in the original worktree. That task joins the existing Game Session main SpotBugs198/200 holds pending the Overseer JVM investigation; do not retry it or change JVM options, JDK or host without that investigation’s direction. Other selected enabled checks and documentation pass; the complete static gate remains unqualified. A common cause is unknown. + - Recurrence on 3 November: public receiving proof 346 crashed Temurin 25.0.5+8 worker `4180380` during `:common-platform-core:spotbugsTest` with `SIGSEGV` in `PhaseIdealLoop::build_loop_late`. Fatal and replay logs are retained privately in R1430/public-static proof 346 JVM and in the original worktree. That task joins the existing Game Session main SpotBugs proof 198/200 holds pending the Overseer JVM investigation; do not retry it or change JVM options, JDK or host without that investigation’s direction. Other selected enabled checks and documentation pass; the complete static gate remains unqualified. A common cause is unknown. - `2026-11-01` (Pacific/Auckland): Two different repository-network failures interrupted one unchanged CI image build. - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. @@ -57,7 +57,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. - `2026-11-03` (Pacific/Auckland): GitHub job-log connector closes transport during CI failure inspection. - - Repeated per-job connector requests failed with `Transport closed` for #3386 Validation and #3388 World/Python jobs while other metadata reads worked. One later #3388 per-job request succeeded during an active workflow, without explaining the failures; whole-run `gh run view --log` still refused before completion. Both #3389 Account jobs125829036896/125829037055 recurred. Read-only per-job `gh api` log retrieval recovered their bytes into private files; any ANSI-capable retrieval must write directly to the private file rather than a terminal. Cause remains unknown. Next: preserve exact request/transport diagnostics on recurrence and repair the connector; do not rerun CI or replace controller operations to recover logs. + - Repeated per-job connector requests failed with `Transport closed` for #3386 Validation and #3388 World/Python jobs while other metadata reads worked. One later #3388 per-job request succeeded during an active workflow, without explaining the failures; whole-run `gh run view --log` still refused before completion. Both #3389 Account jobs `125829036896` / `125829037055` recurred. Read-only per-job `gh api` log retrieval recovered their bytes into private files; any ANSI-capable retrieval must write directly to the private file rather than a terminal. Cause remains unknown. Next: preserve exact request/transport diagnostics on recurrence and repair the connector; do not rerun CI or replace controller operations to recover logs. - `2026-11-04` (Pacific/Auckland): Gameplay controller MCP writes intermittently wait or return transient service errors while the bound CLI remains usable. - Several native-fix and acknowledgement calls exceeded the initial 30-second tool wait; an unsent `deadline_exceeded` fix attempt and an `overloaded` acknowledgement with unknown outcome were also returned. The acknowledgement request was `request_aca253fec2bd7085257f04174863e644`; retrying its exact key/body/binding through the existing Gameplay CLI recovered it. Doctor verified the same clean `1ef2b58` connection and worker identity. No profile switch, worker replacement or grant reset was used. 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 1a91b5dacc..46296912d7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,9 +16,9 @@ PR #3389 now carries the independent Account source/transport foundation on the ### Controlled player-admission transport composition -The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. +The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. -A further prepared [committed-LOGIN composition](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java) replaces the LOGIN caller/currentness doubles with real committed issuance, response recovery, signature/profile verification and current Account owner reads. It uses a current persisted connect scope and physical Redis/PostgreSQL fixtures before calling the same unregistered mTLS receiver and Game Session consumer. Test signing custody, initial response delivery and protected published Game Session/World inputs remain controlled. The additional case also refuses a real Account token-fence revocation despite retained signature bytes and local custody. Compilation, enabled integration Checkstyle/SpotBugs, formatting and documentation checks pass. All five selected PostgreSQL cases, including this additional case, are skipped locally because Docker is unavailable; physical execution remains pending. No default PLAY route or activation is enabled. +A further prepared [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java) replaces the LOGIN caller/currentness doubles with real committed issuance, response recovery, signature/profile verification and current Account owner reads. It uses a current persisted connect scope and physical Redis/PostgreSQL fixtures before calling the same unregistered mTLS receiver and Game Session consumer. Test signing custody, initial response delivery and protected published Game Session/World inputs remain controlled. The additional case also refuses a real Account token-fence revocation despite retained signature bytes and local custody. Compilation, enabled integration Checkstyle/SpotBugs, formatting and documentation checks pass. All five selected PostgreSQL cases, including this additional case, are skipped locally because Docker is unavailable; physical execution remains pending. No default PLAY route or activation is enabled. ### Canonical billing and retention receiving @@ -42,11 +42,11 @@ The earlier published #3389 comparison deliberately left public facade and numer The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). -Preserved source proof310 passes575selected Account units,318passes312facade units and two actual HTTP→Entity compositions,320passes42App PostgreSQL cases,321passes13first-JOIN cases,324passes22PLAYER_ADMISSION owner plus five shared cases, and335passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving343/345 establish793unique selected unit passes after correcting one obsolete first-only generic proof assertion;351passes169selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main198/200 holds remain. Remaining347static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused352transport proof passes all34mTLS client cases (31new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. Published #3390 carries this public source; the terminal-cancellation finding is independently qualified by the coupled356composition in #3389. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. +Preserved source proof 310 passes 575 selected Account units; proof 318 passes 312 facade units and two actual HTTP→Entity compositions; proof 320 passes 42 App PostgreSQL cases; proof 321 passes 13 first-JOIN cases; proof 324 passes 22 PLAYER_ADMISSION owner cases plus five shared cases; and proof 335 passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation 342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving proofs 343/345 establish 793 unique selected unit passes after correcting one obsolete first-only generic proof assertion; proof 351 passes 169 selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest in proof 346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main proof 198/200 holds remain. Remaining proof 347 static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused transport proof 352 passes all 34 mTLS client cases (31 new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. Published #3390 carries this public source; the terminal-cancellation finding is independently qualified by the coupled composition 356 in #3389. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. -Receiving migration-order proof allocates the child-only JOIN diagnostics and existing-membership terminal guard as V1037/V1038 after the actual parent frontier V1036, retaining their SQL bytes and every applied-parent artifact. Proof430 supplies 28 passing canonical scope, first-JOIN and paid-JOIN PostgreSQL cases; its new upgrade case initially failed an incorrect shared-Saga expectation. Corrected proof432 passes the actual parent-history upgrade with unchanged canonical scope/PENDING-intent JSON and row `xmin`, complete prior Flyway rows/checksums, ordered installation of both scripts, a real attempt-diagnostics update and exact SQLSTATE `23514` immutable-caller refusal. Version checking428 and Account generation429 pass;432 also passes enabled integration analysis, formatting and documentation. The failed430 and no-matching-selector431 results remain retained rather than counted as successful aggregate proof. Account has no Common Saga runtime dependency at this boundary; declaring an optional classpath location does not supply those migration resources. +Receiving migration-order proof allocates the child-only JOIN diagnostics and existing-membership terminal guard as V1037/V1038 after the actual parent frontier V1036, retaining their SQL bytes and every applied-parent artifact. Proof 430 supplies 28 passing canonical scope, first-JOIN and paid-JOIN PostgreSQL cases; its new upgrade case initially failed an incorrect shared-Saga expectation. Corrected proof 432 passes the actual parent-history upgrade with unchanged canonical scope/PENDING-intent JSON and row `xmin`, complete prior Flyway rows/checksums, ordered installation of both scripts, a real attempt-diagnostics update and exact SQLSTATE `23514` immutable-caller refusal. Version checking 428 and Account generation 429 pass; proof 432 also passes enabled integration analysis, formatting and documentation. The failed proof 430 and no-matching-selector proof 431 results remain retained rather than counted as successful aggregate proof. Account has no Common Saga runtime dependency at this boundary; declaring an optional classpath location does not supply those migration resources. -The original #3390 validation run `41692144820` exposed an obsolete entitlement-call expectation and an Entity test-fixture SpotBugs warning. Every discovery call joins all independent tenant reads, including failed calls, so the three-call fixture now expects three reads of each tenant. The fixture's generated protobuf request is immutable; narrow accessor/constructor annotations follow the existing fixture convention without changing detector configuration. Receiving proof443 passes all 312 Account facade cases, the physical allocate→later-prepare→selection regression on the carried V1059 schema, enabled Account test and Entity fixture analysis, formatting and documentation (1m38). Both original CI failures remain retained; replacement comparison CI is still required. +The original #3390 validation run `41692144820` exposed an obsolete entitlement-call expectation and an Entity test-fixture SpotBugs warning. Every discovery call joins all independent tenant reads, including failed calls, so the three-call fixture now expects three reads of each tenant. The fixture's generated protobuf request is immutable; narrow accessor/constructor annotations follow the existing fixture convention without changing detector configuration. Receiving Proof 443 passes all 312 Account facade cases, the physical allocate→later-prepare→selection regression on the carried V1059 schema, enabled Account test and Entity fixture analysis, formatting and documentation (1m38). Both original CI failures remain retained; replacement comparison CI is still required. Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The later exact `58a8a10` runtime-image run `41690067116` likewise fails PLAY because Account canonical tenant entitlement authority is unavailable; authenticated cleanup succeeds. Neither metadata-gate success nor local component proof replaces this failed runtime evidence. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. @@ -252,7 +252,7 @@ On Gameplay receiving source `c2f04d797179710e81df08033b16d4f596997e1e`, the sam The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. -The existing [World original-owner composition](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. +The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. ### Original creator validity at the callback boundary diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 65a23ab1be..4820eef768 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -323,7 +323,12 @@ def run_transport_session( raise ProbeOperationalFailure(f"Failed during {session_label}: {exc}") from exc except PlayEntitlementUnavailable: # The temporary CI classification also requires a clean transport close. - session.close() + try: + session.close() + except Exception as close_exc: + raise ProbeOperationalFailure( + f"Failed to close {session_label} after known PLAY refusal: {close_exc}" + ) from close_exc raise except Exception: # A secondary close failure must not hide the primary command failure. @@ -892,7 +897,10 @@ def send_websocket_command_and_expect( ) except ExplicitProtocolFailure as exc: if (label == "PLAY" and line.startswith("PLAY ") - and exc.response == "ERROR ENTITLEMENT_UNAVAILABLE" + and exc.response in { + "ERROR ENTITLEMENT_UNAVAILABLE", + "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.", + } and step_results and step_results[-1]["label"] == "LOGIN" and step_results[-1]["response"].startswith("OK LOGIN")): raise PlayEntitlementUnavailable(exc.response) from exc diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index efe623caf5..0930c88272 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3396,7 +3396,7 @@ const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: step("Known PR 3390 PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; async function verify(mutate = () => {}) { - const data = structuredClone({pr: "3390", run, identity, source, candidate, jobs: [candidate], latest: source, + const data = structuredClone({pr: "3390", run, identity, source, candidate, jobs: [candidate], latest: {...source}, definition: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}); mutate(data); const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, @@ -3443,7 +3443,8 @@ function markerAccepted(overrides = {}) { d => {d.identity.mergeSha = "d".repeat(40);}, d => {d.run.event = "repository_dispatch";}, d => {d.source.run_attempt = 1;}, - d => {d.latest.run_attempt = 3;}, + d => {d.latest.run_attempt = 3; assert.equal(d.source.run_attempt, 2);}, + d => {d.latest.conclusion = "success"; assert.equal(d.source.conclusion, "failure");}, d => {d.source.path = ".github/workflows/spoof.yml";}, d => {d.source.repository.full_name = "attacker/FireMUD";}, d => {d.definition.content = Buffer.from("spoof").toString("base64"); d.definition.size = 5;}, diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 4f7fb02699..2e8e04a307 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -67,8 +67,13 @@ class ClassificationSocket: for label, command, response, prior, expected_type in [ ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.PlayEntitlementUnavailable), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.PlayEntitlementUnavailable), ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE extra", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. more", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.\n", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Another message.", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), ("PLAY", "PLAY demo", "ERROR UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "LOOK demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), ("LOGIN", "LOGIN user secret", "ERROR ENTITLEMENT_UNAVAILABLE", [], smoke_common.ExplicitProtocolFailure), ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE", [], smoke_common.ExplicitProtocolFailure), ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "ERROR LOGIN"}], smoke_common.ExplicitProtocolFailure), @@ -86,9 +91,12 @@ for label, command, response, prior, expected_type in [ # Execute the actual held branch with disposable probe commands: prerequisite # failure must prevent classification, and no failed probe becomes success. -held_branch = (root / "dev-tools/verify-smoke-images.sh").read_text().split( +held_branch_source = (root / "dev-tools/verify-smoke-images.sh").read_text().split( ' run_held_admission_qualification "${COMPOSE_FILES[@]}"', 1 -)[1].rsplit("fi", 1)[0] +)[1] +held_branch, closing_marker, trailing = held_branch_source.rpartition("\nfi\n") +assert closing_marker and not trailing.strip(), "Held smoke branch closing marker changed" +assert held_branch.strip() and "WS_SMOKE_SCRIPT" in held_branch with tempfile.TemporaryDirectory() as directory: probe = Path(directory) / "probe.sh" output = Path(directory) / "output" @@ -1873,6 +1881,28 @@ assert len(close_failure_attempts) == 1 assert close_failure_attempts[0].closed is True +known_play_failure = smoke_common.PlayEntitlementUnavailable("ERROR ENTITLEMENT_UNAVAILABLE") + + +def raise_known_play_failure(_session): + raise known_play_failure + + +try: + run_transport_session( + open_close_failure_session, + raise_known_play_failure, + "known PLAY close failure session", + ) +except smoke_common.ProbeOperationalFailure as exc: + assert type(exc) is smoke_common.ProbeOperationalFailure + assert "Failed to close known PLAY close failure session" in str(exc) + assert isinstance(exc.__cause__, OSError) + assert str(exc.__cause__) == "close failed" +else: + raise AssertionError("A failed transport close must not qualify the PLAY exception") + + class FakeHttpResponse: def __init__(self, body): self.body = body diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 4ce8feca92..207775d4b3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -1215,7 +1215,14 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId } long versionToLock = prior == null ? expectedRowVersion : prior.get("claimed_row_version", Long.class); - var current = intents.lockForProvisioningRecovery(requestId, versionToLock); + AccountSubscriptionCurrentRecord current; + try { + current = intents.lockForProvisioningRecovery(requestId, versionToLock); + } catch (FenceRejectedException refused) { + // A later wallet observation may prevent any further dispatch. Only already retained work + // can use the local settlement fence, and this path never returns a provider-capable claim. + return recoverUndispatchableWork(requestId, versionToLock, prior); + } var original = intents.findCreation(requestId).orElseThrow(); Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); if (now.isBefore(original.createdAt())) { @@ -1317,6 +1324,49 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId return new ClaimResult(Disposition.CLAIMED, claim(original, Objects.requireNonNull(attempt))); } + private ClaimResult recoverUndispatchableWork(UUID requestId, long version, Record prior) { + var current = intents.lockForProvisioningSettlement(requestId, version); + Record work = workForUpdate(requestId); + requireUnmappedProvisioningWork(current, work); + if (prior != null + && !prior.get("attempt_id", UUID.class).equals(work.get("last_attempt_id", UUID.class))) { + return new ClaimResult(Disposition.ATTEMPT_EXPIRED, null); + } + Record retained = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", + work.get("last_attempt_id", UUID.class)); + Instant now = now(); + if (retained == null || now.isBefore(instant(retained, "claimed_at"))) { + throw new FenceRejectedException("Exact retained provisioning attempt is absent or future"); + } + if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { + return new ClaimResult(Disposition.TERMINAL_FAILURE, null); + } + if (!now.isBefore(instant(work, "deadline_at"))) { + return fail(work, "ABSOLUTE_DEADLINE", now); + } + if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { + return fail(work, "ATTEMPT_BUDGET", now); + } + if (work.get("attempt_count", Integer.class) + >= work.get("max_stalled_attempts", Integer.class)) { + return fail(work, "STALLED_WITHOUT_COMMITTED_PROGRESS", now); + } + return new ClaimResult(Disposition.WAITING, null); + } + + private void requireUnmappedProvisioningWork( + AccountSubscriptionCurrentRecord current, Record work) { + if (!current.subscriptionId().equals(work.get("subscription_id", UUID.class)) + || !Objects.equals(current.rowVersion(), work.get("subscription_row_version", Long.class)) + || work.get("last_attempt_id") == null + || current.providerSubscriptionId() != null + || links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Exact unmapped retained provisioning work fence rejected"); + } + } + /** * Inserts a separate immutable provider-dispatch boundary after revalidating the exact live * private worker claim. Only a newly inserted first-dispatch receipt may carry initial-call @@ -1554,9 +1604,27 @@ public ExpectedBinding expectedBinding(String providerId) { public Disposition deferUnresolved(ProvisioningClaim claim) { requireTransaction(); Objects.requireNonNull(claim); - intents.lockForProvisioningRecovery( - claim.creation().requestId(), claim.subscriptionRowVersion()); + var current = + intents.lockForProvisioningSettlement( + claim.creation().requestId(), claim.subscriptionRowVersion()); Record work = workForUpdate(claim.creation().requestId()); + requireUnmappedProvisioningWork(current, work); + Record retained = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", + claim.attemptId()); + if (retained == null + || !claim + .creation() + .equals(intents.findCreation(claim.creation().requestId()).orElseThrow()) + || !claim.creation().requestId().equals(retained.get("request_id", UUID.class)) + || !claim.creation().subscriptionId().equals(retained.get("subscription_id", UUID.class)) + || claim.attemptNumber() != retained.get("attempt_number", Integer.class) + || claim.subscriptionRowVersion() != retained.get("claimed_row_version", Long.class) + || !claim.claimedAt().equals(instant(retained, "claimed_at")) + || !claim.expiresAt().equals(instant(retained, "expires_at"))) { + throw new FenceRejectedException("Exact retained provisioning settlement claim rejected"); + } Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); if (now.isBefore(claim.claimedAt())) { throw new FenceRejectedException("Provisioning clock predates its retained claim"); @@ -1568,12 +1636,12 @@ public Disposition deferUnresolved(ProvisioningClaim claim) { if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(phase)) { return Disposition.TERMINAL_FAILURE; } - if ("RECONCILING".equals(phase)) { - return Disposition.WAITING; - } if (!now.isBefore(instant(work, "deadline_at"))) { return fail(work, "ABSOLUTE_DEADLINE", now).disposition(); } + if ("RECONCILING".equals(phase)) { + return Disposition.WAITING; + } if (!now.isBefore(claim.expiresAt())) { // The exact retained attempt expired without a provider completion. Leave its work and // reservation untouched for the next claimant rather than treating normal expiry as a fault. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java index a453192439..f92bedbf5f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java @@ -212,16 +212,29 @@ public AccountSubscriptionCurrentRecord lockForProvisioningRecovery( */ public AccountSubscriptionCurrentRecord lockForLifecycle( UUID requestId, long expectedRowVersion) { - return lockBinding(requestId, expectedRowVersion, true, true); + return lockBinding(requestId, expectedRowVersion, true, true, true); + } + + /** + * Local settlement only for retained provisioning work. Later wallet observations cannot strand + * its original reservation, but this lock never authorizes a claim or provider dispatch. + */ + AccountSubscriptionCurrentRecord lockForProvisioningSettlement( + UUID requestId, long expectedRowVersion) { + return lockBinding(requestId, expectedRowVersion, true, false, true); } private AccountSubscriptionCurrentRecord lockProvisioningBinding( UUID requestId, long expectedRowVersion, boolean allowProvisioning) { - return lockBinding(requestId, expectedRowVersion, allowProvisioning, false); + return lockBinding(requestId, expectedRowVersion, allowProvisioning, false, false); } private AccountSubscriptionCurrentRecord lockBinding( - UUID requestId, long expectedRowVersion, boolean allowProvisioning, boolean lifecycle) { + UUID requestId, + long expectedRowVersion, + boolean allowProvisioning, + boolean lifecycle, + boolean allowInstrumentObservation) { requireWritableTransaction(); AccountBillingCustomerRecord.requireUuid(requestId); if (expectedRowVersion < 1) { @@ -239,7 +252,7 @@ private AccountSubscriptionCurrentRecord lockBinding( currentForUpdate(original.tenantId()) .orElseThrow(() -> new FenceRejectedException("Current subscription is absent")); boolean instrumentVersionAndStateMatch = - lifecycle + allowInstrumentObservation ? instrument.rowVersion() >= original.reservedInstrumentVersion() && (instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE || instrument.state() == AccountPaymentInstrumentRecord.State.UNAVAILABLE) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index 8d04676614..57451af1d5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -145,6 +145,9 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( CanonicalJoinOperationEvidence operation = joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); requireExactOperation(operation, account.getId(), scope, requestId, callerBinding); + if ("COMMITTED".equals(operation.status())) { + return operation; + } AccountTenantMembership membership = membershipRepository .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) @@ -179,13 +182,7 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( pairAuthorityRepository.readForUpdate(scope.accountId(), scope.tenantId()).orElseThrow(); String outcome; Checkpoint checkpoint; - if ("COMMITTED".equals(operation.status())) { - outcome = operation.outcome(); - checkpoint = - authorityOutboxRepository - .readCheckpoint(operation.terminalProof().eventStreamKey()) - .orElseThrow(); - } else if ("ACTIVE".equals(membership.getLifecycleState())) { + if ("ACTIVE".equals(membership.getLifecycleState())) { outcome = "ALREADY_ACTIVE"; checkpoint = authorityOutboxRepository diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java index 1cc49b0b19..cf2ecd7076 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java @@ -7,8 +7,10 @@ import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -44,12 +46,23 @@ public Result provision(ProvisioningClaim claim, UUID dispatchId, UUID lifecycle requireUuid(dispatchId); requireUuid(lifecycleRequestId); requireNoAmbientTransaction(); - var prepared = - Objects.requireNonNull( - transaction.execute(status -> repository.prepareProviderDispatch(claim, dispatchId))); - var dispatch = - Objects.requireNonNull( - transaction.execute(status -> repository.readProviderDispatch(prepared))); + ProviderDispatch dispatch; + try { + var prepared = + Objects.requireNonNull( + transaction.execute(status -> repository.prepareProviderDispatch(claim, dispatchId))); + dispatch = + Objects.requireNonNull( + transaction.execute(status -> repository.readProviderDispatch(prepared))); + } catch (FenceRejectedException refused) { + // Dispatch remains strictly fenced. A new local transaction may only settle the same retained + // work; stale/current-owner/reservation mismatches still reject there before any write. + Disposition disposition = + Objects.requireNonNull(transaction.execute(status -> repository.deferUnresolved(claim))); + return new Pending( + disposition, + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); + } requireNoAmbientTransaction(); var located = provider.provision(dispatch); if (!(located instanceof StripeHostingSubscriptionProvisioner.Located actual)) { 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 122e67a325..f111f5b157 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 @@ -1046,7 +1046,6 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( CanonicalJoinResult committed = commitCanonicalJoin( consumers, scope, request.requestId(), callerBinding, prepared, observation); - requireCanonicalScopeFresh(consumers, scope); CanonicalJoinTerminalProof proof = committed.proof(); // Publish only after the owner transaction has committed; response loss is exact-retryable. return new JoinPublicProductionResult( @@ -1067,7 +1066,14 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( failure instanceof AuthenticationException authentication ? authentication.getCode() : "ENTITLEMENT_UNAVAILABLE"; - recordCanonicalJoinFailure(scope, request.requestId(), callerBinding, code); + try { + recordCanonicalJoinFailure(scope, request.requestId(), callerBinding, code); + } catch (RuntimeException recordFailure) { + if (recordFailure != failure) failure.addSuppressed(recordFailure); + logger.warn( + "Canonical JOIN failure state could not be recorded; cause={}", + recordFailure.getClass().getSimpleName()); + } if (failure instanceof AuthenticationException authentication) throw authentication; throw new AuthenticationException( code, "Canonical JOIN authority is unavailable; retry the same request", failure); 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 cd88bd7679..98a215bc25 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 @@ -2315,6 +2315,7 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test + @org.springframework.test.annotation.DirtiesContext void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index a6bceb3f40..cd5ee4bd09 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -222,6 +222,7 @@ static void stopEntityRuntime() throws Exception { } @org.junit.jupiter.api.Test + @org.springframework.test.annotation.DirtiesContext void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtlsReads() throws Exception { var entity = requireEntityRuntime(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index b433dbdab2..b38a2c96ef 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -2,6 +2,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.stripe.exception.StripeException; import com.stripe.model.StripeObject; @@ -396,6 +398,208 @@ void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservati .containsEntry("failure_reason", "STALLED_WITHOUT_COMMITTED_PROGRESS"); } + @Test + void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline() { + Fixture f = fixture("1032"); + var original = claim(f, 1); + var originalRows = f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps(); + var reservation = + f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps(); + refreshDisplay(f); + + assertThatThrownBy( + () -> + f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID()))) + .isInstanceOf(FenceRejectedException.class); + var refused = + (AccountHostingSubscriptionProvisioningService.Pending) + service(f).provision(original, UUID.randomUUID(), UUID.randomUUID()); + assertThat(refused.disposition()).isEqualTo(Disposition.WAITING); + assertThat(refused.providerResult()) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); + var waiting = + f.tx() + .execute( + s -> + f.owner() + .claim( + f.creation().requestId(), + original.subscriptionRowVersion(), + UUID.randomUUID())); + assertThat(waiting.disposition()).isEqualTo(Disposition.WAITING); + assertThat(waiting.claim()).isNull(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + f.clock().advance(Duration.ofHours(1)); + + var terminal = + f.tx() + .execute( + s -> + f.owner() + .claim( + f.creation().requestId(), + original.subscriptionRowVersion(), + UUID.randomUUID())); + assertThat(terminal.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(terminal.claim()).isNull(); + assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) + .isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat( + Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) + .intoMap()) + .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") + .containsEntry("failure_reason", "ABSOLUTE_DEADLINE"); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); + assertThat(f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps()) + .isEqualTo(originalRows); + assertThat(f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps()) + .isEqualTo(reservation); + assertThat(Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription")).intoMap()) + .containsEntry("status", "provisioning") + .containsEntry("provider_subscription_id", null) + .containsEntry("terminal_resolution_id", null); + assertThat(f.transport().creates).isZero(); + assertThat(f.transport().searches).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_terminal_resolutions"))) + .isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); + } + + @Test + void displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDeadlineFailure() { + Fixture f = fixture("1032"); + var original = claim(f, 1); + var prepared = + f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID())); + var dispatchRows = + f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps(); + refreshDisplay(f); + + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) + .isInstanceOf(FenceRejectedException.class); + assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) + .isEqualTo(Disposition.WAITING); + f.clock().advance(Duration.ofHours(1)); + assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) + .isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps()) + .isEqualTo(dispatchRows); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); + assertThat(f.transport().creates).isZero(); + } + + @Test + void displayRefreshDoesNotAuthorizeInitialClaimOrDirectDispatchInsert() { + Fixture unclaimed = fixture("1032"); + refreshDisplay(unclaimed); + assertThatThrownBy(() -> claim(unclaimed, 1)).isInstanceOf(FenceRejectedException.class); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_work"))).isZero(); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))) + .isZero(); + + Fixture retained = fixture("1032"); + var original = claim(retained, 1); + refreshDisplay(retained); + // Exercise the unchanged V1032 insertion guard independently of the Java eligibility fence. + assertThatThrownBy( + () -> + retained + .tx() + .execute( + s -> + retained + .dsl() + .execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " + + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", + retained.creation().requestId(), + retained.creation().subscriptionId(), + retained.creation().subscriptionProvisioningRequestId(), + UUID.randomUUID(), + original.attemptId(), + original.subscriptionRowVersion(), + retained.clock().instant().atOffset(ZoneOffset.UTC)))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence"); + assertThat(retained.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) + .isZero(); + assertThat(retained.transport().creates).isZero(); + } + + @Test + void displayRefreshDoesNotLetStaleWorkerSettleReplacementOrRewriteOriginalBinding() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + f.clock().advance(Duration.ofSeconds(11)); + var replacement = claim(f, first.subscriptionRowVersion()); + refreshDisplay(f); + var before = f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps(); + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(first))) + .isInstanceOf(FenceRejectedException.class); + assertThatThrownBy( + () -> + f.tx() + .execute(s -> f.owner().claim(f.creation().requestId(), 1, first.attemptId()))) + .isInstanceOf(FenceRejectedException.class); + assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) + .isEqualTo(before); + // Private claims are not caller-constructible. A controlled changed-creation double still must + // not substitute for the immutable retained original during the local settlement readback. + var changedCreation = mock(AccountSubscriptionCreationRecord.class); + when(changedCreation.requestId()).thenReturn(f.creation().requestId()); + var changedClaim = mock(ProvisioningClaim.class); + when(changedClaim.creation()).thenReturn(changedCreation); + when(changedClaim.attemptId()).thenReturn(replacement.attemptId()); + when(changedClaim.subscriptionRowVersion()).thenReturn(replacement.subscriptionRowVersion()); + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(changedClaim))) + .isInstanceOf(FenceRejectedException.class) + .hasMessage("Exact retained provisioning settlement claim rejected"); + // The database also retains its existing owner-change guard; this component cannot invent an + // unaudited transfer merely to manufacture a changed-current-owner state. + assertThatThrownBy( + () -> + f.tx() + .execute( + s -> + f.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, " + + "owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + f.creation().tenantId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) + .isEqualTo(before); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + assertThat(f.transport().creates).isZero(); + } + + private static void refreshDisplay(Fixture f) { + var instruments = new AccountPaymentInstrumentRepository(f.dsl()); + var original = f.creation(); + var instrument = + instruments + .findByOwner(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(); + in( + f.tx(), + () -> + instruments.recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + instrument.instrumentUuid(), + instrument.accountUuid(), + instrument.rowVersion(), + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new AccountPaymentInstrumentRecord.DisplayMetadata("visa", "4242", 12, 2031), + DIGEST))); + } + private static ProviderDispatch prepareAndRead(Fixture f, ProvisioningClaim claim) { var prepared = f.tx().execute(s -> f.owner().prepareProviderDispatch(claim, UUID.randomUUID())); assertThat(prepared.readyForProviderIo()).isFalse(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index d9a2cda093..2c4ba8c520 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -337,7 +337,15 @@ void activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays() { fixture.dsl.execute( "UPDATE account_join_operations SET outcome_membership_version = 3 WHERE request_id = ?", nextRequest))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains("Terminal canonical JOIN receipt is immutable"); + }); } @Test @@ -452,7 +460,16 @@ void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { fixture.callerBinding, "ALREADY_ACTIVE", proof))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains( + "Canonical JOIN terminal receipt does not match committed owner evidence"); + }); assertThat(fixture.countAll("account_audit_outbox")).isZero(); assertThat( fixture @@ -466,6 +483,59 @@ void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { .isEqualTo("PENDING"); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void committedJoinReplaysStoredEvidenceAfterLaterMembershipChanges(boolean alreadyActive) { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + String originalRequest = alreadyActive ? fixture.prepareAnotherJoin() : fixture.requestId; + var committed = fixture.commitExistingJoin(originalRequest); + assertThat(committed.outcome()).isEqualTo(alreadyActive ? "ALREADY_ACTIVE" : "JOINED"); + + // Controlled historical owner input, not proof of a production leave API. + fixture.seedControlledInactiveOwnerSnapshot(); + var tables = + java.util.List.of( + "account_join_operations", + "account_tenant_membership", + "account_tenant_membership_role_snapshots", + "account_membership_pair_authority", + "account_authority_outbox_events", + "account_authority_outbox_streams", + "account_audit_outbox"); + java.util.function.Supplier storedRows = + () -> + tables.stream() + .map( + table -> + fixture + .dsl + .fetch( + "SELECT xmin::text AS row_version, to_jsonb(t)::text AS row_data FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .intoMaps()) + .toList(); + var inactiveRows = storedRows.get(); + assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); + assertThat(storedRows.get()).isEqualTo(inactiveRows); + + // A real subsequent JOIN owner operation advances the event and restores membership. + var restored = fixture.commitExistingJoin(fixture.prepareAnotherJoin()); + assertThat(restored.terminalProof().eventSequence()).isEqualTo(3L); + assertThat(restored.membershipVersion()).isEqualTo(4L); + var restoredRows = storedRows.get(); + assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.terminalCoordinator.commitCanonicalJoin( + fixture.scope, originalRequest, "different-caller", null, null, null))) + .isInstanceOf(CanonicalJoinOperationConflictException.class); + assertThat(storedRows.get()).isEqualTo(restoredRows); + } + @Test void inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration() { Fixture fixture = newFixture(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java index 9df243230b..50b3c7a81d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -267,7 +267,7 @@ private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean input.setUsername("paid-player-" + UUID.randomUUID()); input.setEmail("paid-player-" + UUID.randomUUID() + "@example.test"); input.setPasswordHash("controlled-hash"); - input.setRole("player"); + // Player role belongs to the canonical tenant membership, not global Account authority. Account player = Objects.requireNonNull(hosting.transaction().execute(status -> accounts.save(input))); var now = hosting.clock().instant(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java index db8088530b..19f88e13d9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -300,7 +300,6 @@ private static Context context() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration", "classpath:db/migration/saga") - .target("1030") .load() .migrate(); var f = CanonicalHostingSubscriptionTestFixture.create(source); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index ad7f8f1ff4..238822168b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -441,7 +441,7 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw logoutAllOperations, securityStateOperations, resetSourceChanges, - null, // Connect scopes are not used by credential/reset owner tests. + null, // Account audit outbox is not used by credential/reset owner tests. null, // JOIN operations are not used by credential/reset owner tests. challenges, null, // Realm grants are not used by primary authentication. @@ -459,7 +459,7 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Email delivery is not used by primary authentication. null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. - null, // Entity Management client is not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. manager); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java index adaa490f63..5a122c2d0b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java @@ -357,7 +357,7 @@ private static FailedHosting failedHosting(AccountControlUiOriginalOrderFixture .reconcile( failedRequest, hosting.creation().requestId(), - 2, + claim.subscriptionRowVersion(), hosting.providerId(), claim.attemptId()) .outcome(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 3d6f9cb464..41c8f08db3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -72,6 +72,7 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( long secondsAfterExpiry) { Instant expiresAt = Instant.parse("2026-11-07T00:00:10Z"); UUID requestId = UUID.randomUUID(); + UUID subscriptionId = UUID.randomUUID(); UUID attemptId = UUID.randomUUID(); var controlledIntents = mock(AccountSubscriptionIntentRepository.class); var controlledRepository = @@ -88,28 +89,58 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( false); var creation = mock(AccountSubscriptionCreationRecord.class); when(creation.requestId()).thenReturn(requestId); + when(creation.subscriptionId()).thenReturn(subscriptionId); + when(controlledIntents.findCreation(requestId)).thenReturn(Optional.of(creation)); + var current = mock(AccountSubscriptionCurrentRecord.class); + when(current.subscriptionId()).thenReturn(subscriptionId); + when(current.rowVersion()).thenReturn(7L); + when(controlledIntents.lockForProvisioningSettlement(requestId, 7L)).thenReturn(current); var claim = mock(ProvisioningClaim.class); when(claim.creation()).thenReturn(creation); when(claim.attemptId()).thenReturn(attemptId); + when(claim.attemptNumber()).thenReturn(2); when(claim.subscriptionRowVersion()).thenReturn(7L); when(claim.claimedAt()).thenReturn(expiresAt.minusSeconds(10)); when(claim.expiresAt()).thenReturn(expiresAt); var retainedWork = mock(Record.class); when(retainedWork.get("last_attempt_id", UUID.class)).thenReturn(attemptId); + when(retainedWork.get("last_attempt_id")).thenReturn(attemptId); + when(retainedWork.get("subscription_id", UUID.class)).thenReturn(subscriptionId); + when(retainedWork.get("subscription_row_version", Long.class)).thenReturn(7L); when(retainedWork.get("phase", String.class)).thenReturn("CLAIMED"); when(retainedWork.get("deadline_at", OffsetDateTime.class)) .thenReturn(expiresAt.plusSeconds(3590).atOffset(ZoneOffset.UTC)); String lockedWorkSql = "SELECT * FROM subscription_provisioning_work WHERE request_id = ? FOR UPDATE"; when(dsl.fetchOne(lockedWorkSql, requestId)).thenReturn(retainedWork); + String linksSql = + "SELECT lifecycle_inflight_request_id, current_receipt_request_id " + + "FROM subscription WHERE subscription_id = ?"; + var links = mock(Record.class); + when(dsl.fetchOne(linksSql, subscriptionId)).thenReturn(links); + String retainedAttemptSql = + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?"; + var retainedAttempt = mock(Record.class); + when(retainedAttempt.get("request_id", UUID.class)).thenReturn(requestId); + when(retainedAttempt.get("subscription_id", UUID.class)).thenReturn(subscriptionId); + when(retainedAttempt.get("attempt_number", Integer.class)).thenReturn(2); + when(retainedAttempt.get("claimed_row_version", Long.class)).thenReturn(7L); + when(retainedAttempt.get("claimed_at", OffsetDateTime.class)) + .thenReturn(expiresAt.minusSeconds(10).atOffset(ZoneOffset.UTC)); + when(retainedAttempt.get("expires_at", OffsetDateTime.class)) + .thenReturn(expiresAt.atOffset(ZoneOffset.UTC)); + when(dsl.fetchOne(retainedAttemptSql, attemptId)).thenReturn(retainedAttempt); TransactionSynchronizationManager.setActualTransactionActive(true); assertThat(controlledRepository.deferUnresolved(claim)).isEqualTo(Disposition.ATTEMPT_EXPIRED); - // Exactly the owner/retained-work locks are allowed: no SQL writes, intent settlement, - // reservation release, or replacement attempt can occur on this return. - verify(controlledIntents).lockForProvisioningRecovery(requestId, 7L); + // Only the exact local owner/work locks, retained attempt and lifecycle ownership reads are + // allowed: no SQL writes, reservation release, or replacement attempt occur on this return. + verify(controlledIntents).lockForProvisioningSettlement(requestId, 7L); + verify(controlledIntents).findCreation(requestId); verify(dsl).fetchOne(lockedWorkSql, requestId); + verify(dsl).fetchOne(linksSql, subscriptionId); + verify(dsl).fetchOne(retainedAttemptSql, attemptId); verifyNoMoreInteractions(controlledIntents, dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index f42e935ed9..12fe7dbb31 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -160,6 +160,60 @@ void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit(bo .commitCanonicalFirstJoin(REQUEST_ID, fixture.scope, CALLER_BINDING, fixture.expectedProof); } + @Test + void committedJoinReturnsStoredEvidenceWithoutReadingOrMutatingCurrentAuthority() { + Fixture fixture = new Fixture(); + var committed = Fixture.committed(fixture.operation, fixture.expectedProof); + when(fixture.accounts.findByAccountUuid(ACCOUNT_ID)).thenReturn(Optional.of(fixture.account)); + when(fixture.operations.findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(committed)); + fixture.startWritableTransaction(); + + var result = + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, null, null, null); + + assertThat(result).isSameAs(committed); + InOrder ordered = inOrder(fixture.accounts, fixture.operations); + ordered.verify(fixture.accounts).findByAccountUuid(ACCOUNT_ID); + ordered.verify(fixture.operations).lockAccount(fixture.account.getId()); + ordered.verify(fixture.operations).findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID); + ordered.verifyNoMoreInteractions(); + verifyNoInteractions( + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void committedJoinStillRejectsChangedRequestOrCallerBinding(boolean changedRequest) { + Fixture fixture = new Fixture(); + String requestId = changedRequest ? "different-request" : REQUEST_ID; + String callerBinding = changedRequest ? CALLER_BINDING : "different-caller"; + when(fixture.accounts.findByAccountUuid(ACCOUNT_ID)).thenReturn(Optional.of(fixture.account)); + when(fixture.operations.findCanonicalEvidenceForUpdateByRequestId(requestId)) + .thenReturn(Optional.of(Fixture.committed(fixture.operation, fixture.expectedProof))); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, requestId, callerBinding, null, null, null)) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) + .hasMessage("Canonical JOIN intent conflicts"); + verifyNoInteractions( + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + @Test void changedCallerUnderGlobalRequestIdConflictsBeforeReturningAnyReceipt() { Fixture fixture = new Fixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 2c069b5dbf..714de0e312 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -125,7 +125,15 @@ void directProducerRefusesWrongPeerBeforeReadingAccountOrSources(String mismatch "AUTH_UNAVAILABLE", () -> f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); - verifyNoInteractions(f.scopes, f.sessions, f.targets, f.entitlements); + verifyNoInteractions( + f.accounts, + f.memberships, + f.tenants, + f.heads, + f.scopes, + f.sessions, + f.targets, + f.entitlements); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java index 32e14ef03f..32590851fa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -13,6 +14,7 @@ import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -108,6 +110,49 @@ void expiredAttemptReturnsTypedPendingWithoutStartingLifecycle(String providerRe verifyNoInteractions(lifecycle); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void refusedDispatchCommitsLocalDeferralWithoutCallingProvider(boolean readbackRefused) { + ProviderDispatch prepared = mock(ProviderDispatch.class); + if (readbackRefused) { + when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); + when(repository.readProviderDispatch(prepared)) + .thenThrow(new FenceRejectedException("wallet observation advanced")); + } else { + when(repository.prepareProviderDispatch(any(), any())) + .thenThrow(new FenceRejectedException("wallet observation advanced")); + } + when(repository.deferUnresolved(claim)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.TERMINAL_FAILURE; + }); + + assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .isEqualTo( + new AccountHostingSubscriptionProvisioningService.Pending( + Disposition.TERMINAL_FAILURE, + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null))); + assertThat(transactions.commits).isEqualTo(readbackRefused ? 2 : 1); + verify(repository).deferUnresolved(claim); + verifyNoInteractions(provider, lifecycle); + } + + @Test + void refusedDispatchCannotHideStaleClaimSettlementFailure() { + when(repository.prepareProviderDispatch(any(), any())) + .thenThrow(new FenceRejectedException("dispatch refused")); + when(repository.deferUnresolved(claim)) + .thenThrow(new FenceRejectedException("stale retained attempt")); + + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(FenceRejectedException.class) + .hasMessage("stale retained attempt"); + assertThat(transactions.commits).isZero(); + verifyNoInteractions(provider, lifecycle); + } + @Test void failedIndependentReadbackNeverCallsProvider() { ProviderDispatch prepared = mock(ProviderDispatch.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 14234211d1..866789cb27 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -746,7 +746,12 @@ void paidMismatchOrUnavailableSourceNeverPublishesOrFallsBack(String failure) { () -> fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "unavailable".equals(failure) + ? "controlled paid source unavailable" + : "Canonical paid first JOIN requires exact current public-join entitlement evidence"); + verify(hosting).readCurrent(fence, observed); verifyNoInteractions(fixture.entitlements); verify(fixture.outbox, never()) .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.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 0df0e651fa..0b804d766d 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.impl; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -1158,6 +1159,82 @@ void canonicalJoinFutureOrExpiredScopeCannotReachMembershipCommit(long seconds) verifyNoInteractions(f.terminal); } + @Test + void canonicalJoinReturnsCommittedReceiptWhenScopeExpiresAfterCommit() { + var f = canonicalJoinFixture(); + var committed = new AtomicBoolean(); + var clock = org.mockito.Mockito.mock(Clock.class); + when(clock.instant()) + .thenAnswer( + invocation -> + Instant.parse(f.scope.evaluatedAt()).plusSeconds(committed.get() ? 120 : 1)); + f.compose(clock); + org.mockito.Mockito.doAnswer( + invocation -> { + if (f.joined.get()) committed.set(true); + return null; + }) + .when(transactionManager) + .commit(org.mockito.ArgumentMatchers.any()); + + var result = f.browserJoin(); + + assertTrue(committed.get()); + assertTrue(result.success()); + assertEquals("JOINED", result.outcomeCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + } + + @ParameterizedTest + @ValueSource( + strings = {"AUTH_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"}) + void canonicalJoinPreservesTypedFailureWhenRecordingFails(String code) { + var f = canonicalJoinFixture(); + var primary = new AuthenticationException(code, "controlled primary source failure"); + var recording = + new org.springframework.dao.DataAccessResourceFailureException( + "controlled recording failure"); + org.mockito.Mockito.doThrow(primary) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doThrow(recording) + .when(accountJoinOperationRepository) + .recordCanonicalAttemptFailure(f.requestId, f.scope, f.binding, "UNAVAILABLE", code); + + var failure = assertThrows(AuthenticationException.class, f::browserJoin); + + assertSame(primary, failure); + assertEquals(code, failure.getCode()); + assertArrayEquals(new Throwable[] {recording}, failure.getSuppressed()); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinPreservesRetryableMappingAndCauseWhenRecordingFails() { + var f = canonicalJoinFixture(); + var primary = new IllegalStateException("controlled primary source failure"); + var recording = new AuthenticationException("ACCOUNT_LOCKED", "controlled recording refusal"); + org.mockito.Mockito.doThrow(primary) + .when(f.sources) + .readCurrentSourceSelection(f.scope.tenantId()); + org.mockito.Mockito.doThrow(recording) + .when(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + + var failure = assertThrows(AuthenticationException.class, f::browserJoin); + + assertEquals("ENTITLEMENT_UNAVAILABLE", failure.getCode()); + assertSame(primary, failure.getCause()); + assertArrayEquals(new Throwable[] {recording}, primary.getSuppressed()); + verifyNoInteractions(f.terminal); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void canonicalJoinRefusesAmbientTransactionsBeforeReadingTheCaller(boolean synchronization) { diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 41d828031e..2f9b0ca8c9 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -18,6 +18,8 @@ import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class AccountRuntimeStubServerCompatibilityTest { private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; @@ -309,12 +311,69 @@ void directTextScopeIssuanceAndJoinRequireRegisteredAccountUuidAndKeepClockSnaps } } - @Test - void alreadyActiveNonAdmittingJoinReturnsMembershipReceiptWithoutGrantingAdmission() + @ParameterizedTest + @ValueSource(strings = {"MISSING", "INACTIVE"}) + void joinedTransitionAdvancesVersionAndRepeatedActiveResultPreservesIt(String lifecycle) throws Exception { + var clock = Clock.fixed(Instant.parse("2026-10-30T12:34:56Z"), ZoneOffset.UTC); + try (var server = new AccountRuntimeStubServer(0, clock)) { + server.mapAccountId("demo@example.com", 7L); + long previousVersion = "MISSING".equals(lifecycle) ? 1L : 3L; + if ("MISSING".equals(lifecycle)) server.setMembershipExists(false); + else server.setMembershipInactive(); + server.setMembershipVersion(previousVersion); + server.setAllowPublicJoin(false); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var scopeRequest = validConnectScopeRequest(accountUuid); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var scope = stub.issueDirectTextConnectScope(scopeRequest); + var request = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId(scope.getConnectScopeId()) + .setRequestId("join-request-1") + .build(); + var before = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + var denied = stub.joinPublicProductionMembership(request); + assertThat(denied.getSuccess()).isFalse(); + assertThat(denied.getOutcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) + .isEqualTo(before); + + server.setAllowPublicJoin(true); + var joined = stub.joinPublicProductionMembership(request); + assertThat(joined.getSuccess()).isTrue(); + assertThat(joined.getOutcomeCode()).isEqualTo("JOINED"); + assertThat(joined.getMembershipVersion()).isEqualTo(previousVersion + 1L); + assertThat(joined.getGameplayAdmissionAllowed()).isTrue(); + var after = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + assertThat(after.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); + assertThat(after.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + + server.setAllowPublicJoin(false); + var repeated = stub.joinPublicProductionMembership(request); + assertThat(repeated.getSuccess()).isTrue(); + assertThat(repeated.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(repeated.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); + assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) + .isEqualTo(after); + } finally { + channel.shutdownNow(); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void alreadyActiveNonAdmittingJoinReturnsMembershipReceiptWithoutGrantingAdmission( + boolean allowPublicJoin) throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { server.mapAccountId("demo@example.com", 7L); server.denyGameplayAdmission(); + server.setAllowPublicJoin(allowPublicJoin); String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); var scopeRequest = validConnectScopeRequest(accountUuid); ManagedChannel channel = diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 6f5fb07718..f1940b49c3 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -361,13 +361,6 @@ public void joinPublicProductionMembership( .setCode("INVALID_ARGUMENT") .setMessage("Direct-text JOIN request is incomplete")) .build()); - } else if (!allowPublicJoin.get()) { - responseObserver.onNext( - JoinPublicProductionMembershipResponse.newBuilder() - .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") - .setAccountId(caller.getAccountId()) - .setTenantId(caller.getTenantId()) - .build()); } else if ("ACTIVE".equals(membershipLifecycleState.get())) { responseObserver.onNext( JoinPublicProductionMembershipResponse.newBuilder() @@ -380,7 +373,15 @@ public void joinPublicProductionMembership( .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) .build()); + } else if (!allowPublicJoin.get()) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .build()); } else { + long joinedMembershipVersion = membershipVersion.incrementAndGet(); membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); responseObserver.onNext( @@ -390,7 +391,7 @@ public void joinPublicProductionMembership( .setAccountId(caller.getAccountId()) .setTenantId(caller.getTenantId()) .setMembershipId("1") - .setMembershipVersion(membershipVersion.get()) + .setMembershipVersion(joinedMembershipVersion) .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) .setGameplayAdmissionAllowed(true) .build()); 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 c7626068fe..c683bde7da 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 @@ -369,6 +369,21 @@ void joinPreservesProducerSuccessAndReplayEvidence(String outcome) throws Except .buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @Test + void joinPreservesAlreadyActiveNonAdmittingReceipt() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var expected = + joinSuccess("ALREADY_ACTIVE", true).toBuilder().setGameplayAdmissionAllowed(false).build(); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); + + assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); + assertThat(expected.getReplayed()).isTrue(); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + @Test void joinDoesNotAcceptJoinedOutcomeWithoutAdmissionFlag() throws Exception { var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); From 2d2800cafd237ffc96ccdbdcc70ce9f360a3b57a Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 14:40:02 +1300 Subject: [PATCH 20/66] Preserve live provisioning leases and canonical direct-text identities --- .../account-service/api-contracts.md | 4 +- .../architecture/system-architecture-cicd.md | 4 +- .../player-access-and-session.md | 12 ++- ...ostingSubscriptionLifecycleRepository.java | 4 + ...CanonicalFirstJoinTerminalCoordinator.java | 4 +- ...AccountCanonicalPublicRealmScopeOwner.java | 8 +- .../service/impl/AccountGrpcService.java | 18 +++- .../service/impl/AccountServiceImpl.java | 12 ++- ...iptionDispatchPostgresIntegrationTest.java | 43 ++++++++ ...nicalFirstJoinTerminalCoordinatorTest.java | 68 ++++++++++++ ...untCanonicalPublicRealmScopeOwnerTest.java | 2 +- .../service/impl/AccountGrpcServiceTest.java | 2 +- .../service/impl/AccountServiceImplTest.java | 4 +- .../gamesession/client/AccountClient.java | 13 ++- .../client/DirectTextConnectScopeTarget.java | 9 +- .../DirectTextAuthenticatedLobbyScope.java | 4 +- ...TextAuthenticatedLobbyIntegrationTest.java | 4 +- .../gamesession/client/AccountClientTest.java | 101 +++++++++++++----- .../DirectTextIssuedConnectScopeTest.java | 4 +- .../DirectTextAuthenticatedLobbyTest.java | 4 +- 20 files changed, 263 insertions(+), 61 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index c8649584ab..ca239a4178 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -464,7 +464,7 @@ The canonical membership, entitlement response shape, freshness, and sequence co Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. -This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation). +This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). ### Private tenant-operation entitlement read @@ -472,7 +472,7 @@ This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Bro The request carries schema version 1, `targetNamespace` matching Account's configured workload namespace, canonical non-nil `tenantId` and `requestId` UUIDs, and an explicit `sourceKind` of exactly `PAID_HOSTING` or `NON_PAID_DEMO`. There is no default, inference or fallback between sources. The paid branch requires a fresh current Account hosting receipt for the exact tenant and matching current tenant-authority evidence; the DEMO branch reads Account's canonical current DEMO entitlement. Account captures complete entitlement facts, tenant-authority/billing-cutoff evidence and outbox checkpoints in the selected owner source transaction. Missing, stale, mismatched or unavailable selected-source authority supplies no success evidence. The response echoes the exact request and carries strict canonical evidence bound to its tenant, request, source kind and authenticated World workload. Repeated transport members each require exactly one value, and unknown fields fail closed. The [closed codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java) owns the 1 KiB request bound, response wire allowance of 64 KiB + 1 KiB + 32 bytes, five-second deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java) owns the 64 KiB canonical content bound. -This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [local source-foundation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). +This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [local source-foundation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). ## Subject-Binding Rules (Normative) diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index b3d35fe25c..f8b0b6b38d 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -435,6 +435,4 @@ CI workflows and operators use distinct credentials for each Kubernetes environm Registry credentials (for GHCR) are shared across environments but access to pull images into each cluster is controlled by Kubernetes secrets and RBAC within that environment. -### Temporary PR 3390 PLAY exception - -PR #3390 alone may pass Smoke Gate for the current exact `pull_request` base/head/merge tuple and latest producer attempt when canonical workflow proof establishes successful held-admission denial qualification, successful backend LOGIN, exactly `ERROR ENTITLEMENT_UNAVAILABLE` on direct backend PLAY, and successful authenticated cleanup. The runtime producer and original smoke step remain failed, all unrelated failures remain blocking, and image export/publication remain skipped. This is merge-only diagnostic acceptance, never runtime qualification or production activation. Remove the classification, producer marker and consumer exception when the Account entitlement cutover permits the normal backend `LOGIN -> PLAY -> LOOK` smoke to pass. Capability and proof limits are recorded in the [player access tracker](../project-management/implementation-tracking/player-access-and-session.md). +The required Smoke Gate needs qualified runtime smoke under the contract above. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-pr-3390-play-exception) records the temporary merge-only limitation for the unfinished cutover; it supplies no runtime qualification or image-publication authority. 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 9ac4b4fdde..3190e10129 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,10 +6,20 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -PR #3390 currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](../../architecture/system-architecture-cicd.md#temporary-pr-3390-play-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. +PR #3390 currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-pr-3390-play-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. +### Temporary PR 3390 PLAY exception + +PR #3390 alone may pass Smoke Gate for the current exact `pull_request` base/head/merge tuple and latest producer attempt when canonical workflow proof establishes successful held-admission denial qualification, successful backend LOGIN, one of the two exact accepted direct-backend PLAY responses (`ERROR ENTITLEMENT_UNAVAILABLE` alone or followed by `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.`), and successful authenticated cleanup. The runtime producer and original smoke step remain failed, all unrelated failures remain blocking, and image export/publication remain skipped. This is merge-only diagnostic acceptance, never runtime qualification or production activation. Remove the classification, producer marker and consumer exception when the Account entitlement cutover permits the normal backend `LOGIN -> PLAY -> LOOK` smoke to pass. + +### Direct-text scope and JOIN identifier cutover + +The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. + +Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby remains unregistered; source custody, genuine cross-service scope/JOIN qualification and public admission remain unfinished. The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. + ### Receiving review boundaries PR #3389 now carries the independent Account source/transport foundation on the supported `develop` runtime. Its unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery do not replace live PLAY authority. This draft PR #3390 retains canonical UUID schema retirement, the public facade/JOIN receiving cutover, initial hosting provider-write source with its focused units, and dependent physical proof; it remains unfinished until a functioning canonical PLAY replacement is qualified. PR #3403 retains private FRESH/World preparation. The source and prior corrections remain preserved through normal ancestry; the changed comparisons do not reset review counts or grant current coverage. No new caller custody, runtime registration, admission or activation is established by the reconstruction. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 207775d4b3..2da4599bcc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -1346,6 +1346,10 @@ private ClaimResult recoverUndispatchableWork(UUID requestId, long version, Reco if (!now.isBefore(instant(work, "deadline_at"))) { return fail(work, "ABSOLUTE_DEADLINE", now); } + if ("CLAIMED".equals(work.get("phase", String.class)) + && now.isBefore(instant(work, "lease_expires_at"))) { + return new ClaimResult(Disposition.WAITING, null); + } if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { return fail(work, "ATTEMPT_BUDGET", now); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index 213caea108..5e7007c863 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -203,8 +203,8 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( membership = membershipRepository.restoreFreshMembershipForJoin( scope.accountId(), scope.tenantId(), membership); - List restoredRoles = new java.util.ArrayList<>(roles.roles()); - if (!restoredRoles.contains("player")) restoredRoles.add("player"); + // Public enrollment grants only player authority, never retained elevated tenant roles. + List restoredRoles = List.of("player"); roles = roleSnapshotRepository.replaceCanonical( membership, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index d4a436730a..fd7a46a759 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -158,11 +158,11 @@ public RealmScope issueDirectTextScope( "CONNECT_CONTEXT_INVALID", "Direct caller correlation is invalid"); } try { - UUID session = UUID.fromString(caller.sessionId()); - if (!session.toString().equals(caller.sessionId()) || new UUID(0L, 0L).equals(session)) { - throw new IllegalArgumentException("Invalid session correlation"); + long session = Long.parseLong(caller.sessionId()); + if (session <= 0 || !caller.sessionId().matches("[0-9]+")) { + throw new NumberFormatException("Invalid transport session"); } - } catch (IllegalArgumentException failure) { + } catch (NumberFormatException failure) { throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "Direct caller session is invalid"); } 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 bdf3f17b00..e3ac2ec028 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 @@ -327,12 +327,28 @@ private DirectTextCallerContext directTextCaller( throw new InvalidRequestException("playableStateScope must be SHARED or ISOLATED", null); } UUID gameInstanceId = requireCanonicalUuid(context.getGameInstanceId(), "gameInstanceId"); - String sessionId = requireCanonicalUuid(context.getSessionId(), "sessionId").toString(); + String sessionId = requireDirectTextTransportSession(context.getSessionId()); String requestId = requireText(context.getRequestId(), "requestId"); return new DirectTextCallerContext( accountUuid, tenantId, realmId, namespaceId, scope, gameInstanceId, sessionId, requestId); } + private static String requireDirectTextTransportSession(String value) { + if (value == null || value.length() > 32) { + throw new InvalidRequestException("sessionId must be a bounded numeric transport ID", null); + } + try { + long session = Long.parseLong(value); + if (session <= 0 || !value.matches("[0-9]+")) { + throw new NumberFormatException("Invalid transport session"); + } + } catch (NumberFormatException malformed) { + throw new InvalidRequestException( + "sessionId must be a positive numeric transport ID", malformed); + } + return value; + } + private UUID requireCanonicalRealmId(String value) { return requireCanonicalUuid(value, "realmId"); } 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 21aab604cc..b1fda10e97 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 @@ -1130,7 +1130,9 @@ public JoinPublicProductionResult joinPublicProductionFromGameSession( || caller.accountId() == null || NIL_ACCOUNT_UUID.equals(caller.accountId()) || !StringUtils.hasText(caller.sessionId()) - || AccountUuidText.parseOrNull(caller.sessionId()) == null + || caller.sessionId().length() > 32 + || !caller.sessionId().matches("[0-9]+") + || !isPositiveTransportSession(caller.sessionId()) || !StringUtils.hasText(caller.requestId()) || request == null || !caller.requestId().equals(request.requestId())) { @@ -1154,6 +1156,14 @@ public JoinPublicProductionResult joinPublicProductionFromGameSession( () -> requireCanonicalDirectPeer(consumers)); } + private static boolean isPositiveTransportSession(String value) { + try { + return Long.parseLong(value) > 0; + } catch (NumberFormatException malformed) { + return false; + } + } + private void requireCanonicalDirectPeer(CanonicalScopeConsumers consumers) { var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.current(); if (peer == null diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index d63de7a7d8..8f3d636e5a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -393,6 +393,43 @@ void realInitialSdkCreateFlowsThroughExistingLifecycleCommitAndIndependentCurren assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(3); } + @Test + void liveFinalBudgetDispatchSurvivesDisplayRefreshAndCompetingClaim() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + f.clock().advance(Duration.ofSeconds(11)); + var second = claim(f, first.subscriptionRowVersion()); + f.clock().advance(Duration.ofSeconds(11)); + var finalClaim = claim(f, second.subscriptionRowVersion()); + assertThat(finalClaim.attemptNumber()).isEqualTo(3); + f.transport().duringCreate = + () -> { + refreshDisplay(f); + var competing = + f.tx() + .execute( + s -> + f.owner() + .claim( + f.creation().requestId(), + finalClaim.subscriptionRowVersion(), + UUID.randomUUID())); + assertThat(competing.disposition()).isEqualTo(Disposition.WAITING); + assertThat(competing.claim()).isNull(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) + .isZero(); + }; + + var result = + (AccountHostingSubscriptionProvisioningService.Committed) + service(f).provision(finalClaim, UUID.randomUUID(), UUID.randomUUID()); + assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(f.transport().creates).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isEqualTo(3); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isOne(); + } + @Test void lostCreateResponseRecoversAfterTransientEmptySearchWithoutRecreating() { Fixture f = fixture("1032"); @@ -1020,6 +1057,7 @@ private static final class Transport implements StripeResponseGetter { private final Clock clock; private boolean exists; private boolean loseCreateResponse; + private Runnable duringCreate; private int emptySearchesRemaining; private int searches; private int creates; @@ -1093,6 +1131,11 @@ public T request( creation.planQuote().providerPriceId(), "quantity", creation.planQuote().providerQuantity()))); + if (duringCreate != null) { + Runnable action = duringCreate; + duringCreate = null; + action.run(); + } if (loseCreateResponse) { throw org.mockito.Mockito.mock(StripeException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index cb66c06b0f..305c0855ff 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -189,6 +189,74 @@ void terminalJoinReturnsStoredEvidenceWithoutReadingOrMutatingCurrentAuthority(S fixture.eventProducer); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void inactiveJoinRestoresOnlyPlayerWithoutRegrantingRetainedElevatedRoles( + boolean retainedPlayerRole) { + Fixture fixture = new Fixture(); + fixture.arrangePending(); + AccountTenantMembership inactive = fixture.membership(fixture.account); + inactive.setLifecycleState("INACTIVE"); + inactive.setGameplayAdmissionAllowed(false); + inactive.setMembershipVersion(1L); + List retainedRoles = + retainedPlayerRole + ? List.of("designer", "moderator", "player", "tenantAdmin") + : List.of("designer", "moderator", "tenantAdmin"); + RoleSnapshot inactiveRoles = + new RoleSnapshot( + 17L, null, 73L, 1L, retainedRoles, ACCOUNT_ID, TENANT_ID, fixture.provenance); + when(fixture.memberships.findFreshMembershipForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(inactive)); + when(fixture.roles.findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, fixture.provenance, 73L, 1L)) + .thenReturn(Optional.of(inactiveRoles)); + when(fixture.memberships.restoreFreshMembershipForJoin(ACCOUNT_ID, TENANT_ID, inactive)) + .thenReturn(fixture.membership); + when(fixture.eventProducer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.positivePair(fixture.event.eventId(), fixture.event.eventDigest()), + null, + null, + null)) + .thenReturn(fixture.checkpoint); + var committed = Fixture.committed(fixture.operation, fixture.expectedProof); + when(fixture.operations.commitCanonicalJoin( + REQUEST_ID, fixture.scope, CALLER_BINDING, "JOINED", fixture.expectedProof)) + .thenReturn(committed); + fixture.startWritableTransaction(); + + var result = + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, null, null, null); + + assertThat(result).isSameAs(committed); + InOrder ordered = inOrder(fixture.roles, fixture.eventProducer); + ordered + .verify(fixture.roles) + .findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, fixture.provenance, 73L, 1L); + ordered + .verify(fixture.roles) + .replaceCanonical( + fixture.membership, ACCOUNT_ID, TENANT_ID, fixture.provenance, 2L, List.of("player")); + ordered + .verify(fixture.eventProducer) + .publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.positivePair(fixture.event.eventId(), fixture.event.eventDigest()), + null, + null, + null); + MembershipEvent restoredEvent = + MembershipAuthorityEventV1Codec.verify( + new String(fixture.event.payload(), StandardCharsets.UTF_8)); + assertThat(restoredEvent.roles()).containsExactly("player"); + assertThat(inactiveRoles.roles()).containsExactlyElementsOf(retainedRoles); + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) void committedJoinStillRejectsChangedRequestOrCallerBinding(boolean changedRequest) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index d90eec8606..78e4a0937b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -185,7 +185,7 @@ private static DirectTextCallerContext directCaller(Target target) { target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), - "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "00042", "direct-request"); } 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 6610dfbc34..f2246f2eb3 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 @@ -89,7 +89,7 @@ class AccountGrpcServiceTest { private static final UUID DIRECT_TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID DIRECT_INSTANCE = UUID.fromString("44444444-4444-4444-8444-444444444444"); - private static final String DIRECT_SESSION = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + private static final String DIRECT_SESSION = "00042"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/game-session-service", 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 c46ed0d5db..f09666822e 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 @@ -1356,7 +1356,7 @@ void canonicalDirectJoinRejectsAnyCallerTargetMismatchBeforeIntent(String field) field.equals("namespace") ? UUID.randomUUID() : f.scope.playableStateNamespaceId(), field.equals("scope") ? "ISOLATED" : f.scope.playableStateScope(), field.equals("instance") ? UUID.randomUUID() : f.scope.gameInstanceId(), - UUID.randomUUID().toString(), + "00042", f.requestId); assertEquals( "CONNECT_SCOPE_MISMATCH", @@ -1671,7 +1671,7 @@ private DirectTextCallerContext directCaller(String id) { scope.playableStateNamespaceId(), scope.playableStateScope(), scope.gameInstanceId(), - UUID.randomUUID().toString(), + "00042", id); } } 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 531d015467..c8741a5e58 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 @@ -32,7 +32,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.JwtClaims; -import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.gamesession.service.SessionIdParsing; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; @@ -308,14 +308,17 @@ private boolean hasDirectTextCallerShape(PlayerExecutionContext context) { } try { JwtClaims.requireCanonicalAccountUuid(context.getAccountId(), "accountId"); - RequestIdValidation.requirePositiveLong(context.getTenantId(), "tenantId"); + DirectTextConnectScopeTarget.requireUuid(context.getTenantId(), "tenantId"); DirectTextConnectScopeTarget.requireUuid(context.getRealmId(), "realmId"); DirectTextConnectScopeTarget.requireUuid( context.getPlayableStateNamespaceId(), "playableStateNamespaceId"); DirectTextConnectScopeTarget.requireScope(context.getPlayableStateScope()); - RequestIdValidation.requirePositiveLong(context.getGameInstanceId(), "gameInstanceId"); - return isBoundedText(context.getSessionId(), 128) - && isBoundedText(context.getRequestId(), 128); + DirectTextConnectScopeTarget.requireUuid(context.getGameInstanceId(), "gameInstanceId"); + if (!isBoundedText(context.getSessionId(), 32) || !context.getSessionId().matches("[0-9]+")) { + return false; + } + SessionIdParsing.require(context.getSessionId()); + return isBoundedText(context.getRequestId(), 128); } catch (IllegalArgumentException ex) { return false; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java index 625f8e4880..9ed370dbe3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.gamesession.client; import java.util.UUID; -import net.firedevops.firemud.common.security.RequestIdValidation; /** Server-resolved routing evidence, not authentication or gameplay admission authority. */ public record DirectTextConnectScopeTarget( @@ -15,13 +14,13 @@ public record DirectTextConnectScopeTarget( long catalogRevision, long pointerVersion) { public DirectTextConnectScopeTarget { - RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); + requireUuid(tenantId, "tenantId"); requireText(worldSlug, "worldSlug", 128); requireText(realmSlug, "realmSlug", 128); requireUuid(realmId, "realmId"); requireUuid(playableStateNamespaceId, "playableStateNamespaceId"); requireScope(playableStateScope); - RequestIdValidation.requirePositiveLong(gameInstanceId, "gameInstanceId"); + requireUuid(gameInstanceId, "gameInstanceId"); if (catalogRevision < 1 || pointerVersion < 1) { throw new IllegalArgumentException("routing revisions must be positive"); } @@ -34,7 +33,9 @@ static void requireText(String value, String name, int maxLength) { } static void requireUuid(String value, String name) { - if (value == null || !UUID.fromString(value).toString().equals(value)) { + if (value == null + || !UUID.fromString(value).toString().equals(value) + || new UUID(0L, 0L).equals(UUID.fromString(value))) { throw new IllegalArgumentException(name + " must be a canonical UUID"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java index 40b7f5a350..93902d97a3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java @@ -175,13 +175,13 @@ public static DirectTextAuthenticatedLobbyScope decode(byte[] bytes) { public static DirectTextConnectScopeTarget targetFor(CanonicalPlayableTarget target) { Objects.requireNonNull(target); return new DirectTextConnectScopeTarget( - Long.toString(target.gameSessionTenantId()), + target.canonicalTenantId().toString(), target.worldSlug(), target.realmSlug(), target.realmId().toString(), target.playableStateNamespaceId().toString(), target.playableStateScope(), - Long.toString(target.gameInstanceId()), + target.canonicalGameInstanceId().toString(), target.catalogRevision(), target.pointerVersion()); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java index f7b89c287a..812f909908 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -814,7 +814,7 @@ private static JoinPublicProductionMembershipResponse positive() { .setSuccess(true) .setOutcomeCode("JOINED") .setAccountId(ACCOUNT.toString()) - .setTenantId("101") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("90") .setMembershipVersion(3) .setMembershipAuthorityGeneration(1) @@ -833,7 +833,7 @@ private static CanonicalPlayableTarget target() { return new CanonicalPlayableTarget( "gameplay", "studio", - UUID.randomUUID(), + UUID.fromString("22222222-2222-4222-8222-222222222222"), "forest", "Forest", UUID.randomUUID(), 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 c683bde7da..1035c9a6ff 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 @@ -66,10 +66,10 @@ void directTextScopeCapturesExactCompleteRequest() throws Exception { .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") .build(); when(fixture.initialStub().issueDirectTextConnectScope(any())).thenReturn(expected); - // Session/request are bounded opaque text, not numeric IDs. Preserve their exact bytes. + // The numeric transport session retains its exact bytes, including leading zeros. var context = directTextContext().toBuilder() - .setSessionId(" transport-session ") + .setSessionId("00042") .setRequestId(" scope-request ") .build(); var target = directTextTarget(); @@ -82,13 +82,13 @@ void directTextScopeCapturesExactCompleteRequest() throws Exception { .isEqualTo( IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(context) - .setTenantId("22") + .setTenantId("22222222-2222-4222-8222-222222222222") .setWorldSlug("demo-world") .setRealmSlug("production") .setRealmId(target.realmId()) .setPlayableStateNamespaceId(target.playableStateNamespaceId()) .setPlayableStateScope("SHARED") - .setGameInstanceId("9") + .setGameInstanceId("44444444-4444-4444-8444-444444444444") .setCatalogRevision(7L) .setPointerVersion(4L) .build()); @@ -197,7 +197,15 @@ void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { var target = directTextTarget(); String[][] malformed = { - {"0", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "9"}, + { + "0", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444" + }, { "tenant", "world", @@ -205,31 +213,71 @@ void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9" + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + " ", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444" }, - {"22", " ", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "9"}, { - "22", + "22222222-2222-4222-8222-222222222222", "w".repeat(129), "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9" + "44444444-4444-4444-8444-444444444444" }, { - "22", + "22222222-2222-4222-8222-222222222222", "world", "r".repeat(129), target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9" + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + "realm", + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444" }, - {"22", "world", "realm", "realm", target.playableStateNamespaceId(), "SHARED", "9"}, - {"22", "world", "realm", target.realmId(), "namespace", "SHARED", "9"}, - {"22", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "shared", "9"}, - {"22", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "0"} + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + "namespace", + "SHARED", + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "shared", + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "0" + } }; for (var fields : malformed) { assertThatThrownBy( @@ -242,26 +290,26 @@ void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { assertThatThrownBy( () -> new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 0L, 4L)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 7L, -1L)) .isInstanceOf(IllegalArgumentException.class); @@ -407,7 +455,7 @@ void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Excepti .setSuccess(false) .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") .setAccountId(ACCOUNT_UUID) - .setTenantId("22") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("0") .build(); for (var expected : @@ -429,13 +477,14 @@ void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Excepti } @Test - void joinAcceptsBoundedOpaqueIdentityWithoutTrimmingOrRegeneration() throws Exception { + void joinPreservesBoundedNumericTransportIdentityWithoutTrimmingOrRegeneration() + throws Exception { var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); var requestId = " " + "r".repeat(126) + " "; var scopeId = " " + "s".repeat(2046) + " "; var context = directTextContext().toBuilder() - .setSessionId("s".repeat(128)) + .setSessionId("0".repeat(30) + "42") .setRequestId(requestId) .build(); var expected = joinSuccess("JOINED", false); @@ -692,13 +741,13 @@ void joinRechecksExpiryDuringChannelReloadBeforeRetry() throws Exception { private static DirectTextConnectScopeTarget directTextTarget() { return new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "demo-world", "production", "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", "42d234a2-7487-4dda-a7e5-a3831214328e", "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 7L, 4L); } @@ -707,7 +756,7 @@ private static PlayerExecutionContext directTextContext() { var target = directTextTarget(); return PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setSessionId("transport-session") + .setSessionId("00042") .setTenantId(target.tenantId()) .setRealmId(target.realmId()) .setPlayableStateNamespaceId(target.playableStateNamespaceId()) @@ -723,7 +772,7 @@ private static JoinPublicProductionMembershipResponse joinSuccess( .setSuccess(true) .setOutcomeCode(outcome) .setAccountId(ACCOUNT_UUID) - .setTenantId("22") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("81") .setMembershipVersion(12L) .setMembershipAuthorityGeneration(3L) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java index 23eb9a459e..91158e2764 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java @@ -148,13 +148,13 @@ private static IssueDirectTextConnectScopeResponse response( private static DirectTextConnectScopeTarget target() { return new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "demo-world", "production", "00000000-0000-4000-8000-000000000101", "00000000-0000-4000-8000-000000000102", "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 7L, 4L); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index cf6604fcca..ec33654ac1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -667,7 +667,7 @@ private static JoinPublicProductionMembershipResponse positive() { .setSuccess(true) .setOutcomeCode("JOINED") .setAccountId(ACCOUNT.toString()) - .setTenantId("101") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("90") .setMembershipVersion(3) .setMembershipAuthorityGeneration(1) @@ -679,7 +679,7 @@ private static CanonicalPlayableTarget target(String display) { return new CanonicalPlayableTarget( "gameplay", "studio", - UUID.randomUUID(), + UUID.fromString("22222222-2222-4222-8222-222222222222"), "forest", display, UUID.randomUUID(), From f6c435e96886a9134630b0abba48c2440927a030 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 15:19:14 +1300 Subject: [PATCH 21/66] Bound transitional PLAY gate and correct transport fixtures --- .github/workflows/runtime-images.yml | 9 ++-- .github/workflows/smoke.yml | 35 ++++++++++------ .../architecture/system-architecture-cicd.md | 4 +- .../player-access-and-session.md | 6 +-- .../pr-required-gate-context-contract.sh | 42 ++++++++++++------- .../AccountApplicationIntegrationTest.java | 4 +- ...PlayerAdmissionEntitlementComposition.java | 4 +- 7 files changed, 64 insertions(+), 40 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 33ca465b76..43de0a6d0a 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1781,18 +1781,19 @@ jobs: exit 1 fi - # Temporary PR #3390 diagnostic evidence, not runtime qualification. The + # Canonical-transition diagnostic evidence, not runtime qualification. The # original failed step and the final required-smoke failure remain red. - - name: Known PR 3390 PLAY failure with successful authenticated cleanup + - name: Known canonical transition PLAY failure with successful authenticated cleanup if: >- ${{ always() && github.event_name == 'pull_request' && - github.repository == 'benhook1013/FireMUD' && github.event.pull_request.number == 3390 && + github.repository == 'benhook1013/FireMUD' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition') && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.runtime-smoke.outcome == 'failure' && steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && steps.runtime-cleanup.outcome == 'success' }} run: | - echo '### Temporary PR #3390 PLAY exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" - name: Require successful runtime smoke and authenticated cleanup diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index ad1d7aa25e..6f9184f82e 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -348,7 +348,7 @@ jobs: if (!changesHealthy) { headline = `${statusIcon(smokeGateStatus)} Smoke Gate completed with ${smokeGateStatus}; scope detection was ${changesStatus}`; } else if (knownPlayException) { - headline = "⚠️ Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Temporary PR #3390 exception accepted; no runtime qualification or publication."; + headline = "⚠️ Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Canonical PLAY transition exception accepted; no runtime qualification or publication."; } else if (fullEnabled) { headline = `${statusIcon(smokeGateStatus)} Full-stack smoke completed with Smoke Gate: ${smokeGateStatus}`; } @@ -608,7 +608,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "7d5df7eee20eea25e006ca62d2707613eeedce0d43f6985e14c3f2f66eead21f"; + const canonicalRuntimeWorkflowSha256 = "e337cb510a2ac861f823e62ad4e31026ab1c0734f4103f21b4d98a14c30eefb4"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = `${owner}/${repo}`; @@ -775,9 +775,9 @@ jobs: latest.status === "completed" && latest.conclusion === "success"; } - // Temporary #3390 diagnostic acceptance never becomes passing producer proof. + // Canonical-transition diagnostic acceptance never becomes passing producer proof. async function verifyKnownPlayFailure(run, candidate, identity) { - if (prNumber !== "3390" || repositoryName !== "benhook1013/FireMUD" || + if (repositoryName !== "benhook1013/FireMUD" || run.event !== "pull_request") return false; if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; const { data: source } = await withTransientGitHubRetry( @@ -825,7 +825,7 @@ jobs: "Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup", ]; - const markerName = "Known PR 3390 PLAY failure with successful authenticated cleanup"; + const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; const steps = job.steps ?? []; const exactlyOne = (name, conclusion) => steps.filter((step) => step.name === name && step.status === "completed" && step.conclusion === conclusion @@ -855,8 +855,19 @@ jobs: "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) ); - return latest.id === source.id && latest.run_attempt === source.run_attempt && - latest.status === "completed" && latest.conclusion === "failure"; + if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || + latest.status !== "completed" || latest.conclusion !== "failure") return false; + // The producer marker attests the source event label under the fingerprinted + // workflow. Recheck the live PR label here so removal closes the exception. + const { data: currentPullRequest } = await withTransientGitHubRetry( + "current canonical transition label lookup", + () => github.rest.pulls.get({ owner, repo, pull_number: Number(prNumber) }) + ); + return currentPullRequest.state === "open" && + currentPullRequest.head?.sha === identity.headSha && + currentPullRequest.base?.ref === identity.baseRef && + Array.isArray(currentPullRequest.labels) && + currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"); } // Commit objects are immutable; mutable PR/base reads stay fresh. @@ -1160,24 +1171,24 @@ jobs: if (await isCurrentPullRequestObsolete("Stopping obsolete failed smoke gate for")) { return; } - if (matching.conclusion === "failure" && prNumber === "3390" && + if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && matching.event === "pull_request") { - const jobs = await withTransientGitHubRetry("temporary PLAY failure jobs lookup", () => + const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { owner, repo, run_id: matching.id, attempt_number: matching.run_attempt, per_page: 100, }) ); const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); if (candidate && await verifyKnownPlayFailure(matching, candidate, currentIdentity)) { - const freshIdentity = await resolveCurrentIdentity("Stopping stale temporary PLAY exception"); + const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { currentIdentity = freshIdentity; continue smokeGatePolling; } core.setOutput("known_play_exception", "true"); - core.warning("Temporary PR #3390 exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); - await core.summary.addHeading("Temporary PR #3390 PLAY exception accepted") + core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); + await core.summary.addHeading("Canonical PLAY transition exception accepted") .addRaw("Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.") .write(); return; diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index f8b0b6b38d..2e6793f53a 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,7 +88,7 @@ A typed runtime refresh hands off publication explicitly after its required cred The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose source `pull_request` event and current live PR both carry the `canonical-play-transition` label, only for the exact verified PR-event base/head/merge tuple and latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The step-independent producer guarantee is bound to one SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. This single fingerprint is part of the owning workflows, not a separate proof registry. @@ -435,4 +435,4 @@ CI workflows and operators use distinct credentials for each Kubernetes environm Registry credentials (for GHCR) are shared across environments but access to pull images into each cluster is controlled by Kubernetes secrets and RBAC within that environment. -The required Smoke Gate needs qualified runtime smoke under the contract above. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-pr-3390-play-exception) records the temporary merge-only limitation for the unfinished cutover; it supplies no runtime qualification or image-publication authority. +The required Smoke Gate normally needs qualified runtime smoke under the contract above. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. 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 3190e10129..65cb789794 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -PR #3390 currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-pr-3390-play-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. +PR #3390 currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-canonical-play-transition-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for labeled nonproduction cutover PR merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. -### Temporary PR 3390 PLAY exception +### Temporary canonical PLAY transition exception -PR #3390 alone may pass Smoke Gate for the current exact `pull_request` base/head/merge tuple and latest producer attempt when canonical workflow proof establishes successful held-admission denial qualification, successful backend LOGIN, one of the two exact accepted direct-backend PLAY responses (`ERROR ENTITLEMENT_UNAVAILABLE` alone or followed by `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.`), and successful authenticated cleanup. The runtime producer and original smoke step remain failed, all unrelated failures remain blocking, and image export/publication remain skipped. This is merge-only diagnostic acceptance, never runtime qualification or production activation. Remove the classification, producer marker and consumer exception when the Account entitlement cutover permits the normal backend `LOGIN -> PLAY -> LOOK` smoke to pass. +The existing canonical-cutover stack may opt into the [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) with the `canonical-play-transition` label. The source event and live PR must both have it. This includes #3390 and, only if deliberately labeled, dependent #3405, #3409, #3407, #3408 and #3410; #3403 is not approved for the exception. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. ### Direct-text scope and JOIN identifier cutover diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 7a21caff5b..819f01e0c2 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -548,10 +548,10 @@ if guard["env"] != { }: raise SystemExit("Terminal guard must consume native Actions outcomes, never command-written outputs") Path(sys.argv[2] + ".guard").write_text(guard["with"]["script"]) -marker = next(step for step in steps if step.get("name") == "Known PR 3390 PLAY failure with successful authenticated cleanup") +marker = next(step for step in steps if step.get("name") == "Known canonical transition PLAY failure with successful authenticated cleanup") for clause in ( "always()", "github.event_name == 'pull_request'", "github.repository == 'benhook1013/FireMUD'", - "github.event.pull_request.number == 3390", "needs.image-meta.outputs.runtime_smoke_required == 'true'", + "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", "needs.image-meta.outputs.runtime_smoke_required == 'true'", "steps.runtime-smoke.outcome == 'failure'", "steps.runtime-cleanup.outcome == 'success'", "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", ): @@ -3393,7 +3393,7 @@ const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); -const identity = {headSha, baseSha, mergeSha}; +const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; const run = {id: 99, run_attempt: 2, event: "pull_request"}; const failures = ["Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup"]; const step = (name, conclusion) => ({name, conclusion, status: "completed"}); @@ -3403,35 +3403,38 @@ const source = {...run, status: "completed", conclusion: "failure", path: workfl const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: canonicalSmokeJobName, status: "completed", conclusion: "failure", check_run_url: `https://api.github.com/repos/${repositoryName}/check-runs/123`, steps: [...failures.map(name => step(name, "failure")), step("Stop smoke stack", "success"), - step("Known PR 3390 PLAY failure with successful authenticated cleanup", "success"), + step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; async function verify(mutate = () => {}) { - const data = structuredClone({pr: "3390", run, identity, source, candidate, jobs: [candidate], latest: {...source}, + const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, + currentPullRequest: {state: "open", head: {sha: headSha}, base: {ref: "develop"}, labels: [{name: "canonical-play-transition"}]}, definition: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}); mutate(data); const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, rest: {actions: {getWorkflow: async () => ({data: {id: 7, path: workflowPath, name: "Build Runtime Images"}}), - getWorkflowRun: async () => ({data: data.latest})}, repos: {getContent: async () => ({data: data.definition})}}}; + getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, repos: {getContent: async () => ({data: data.definition})}}}; return new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", "canonicalRuntimeWorkflowSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( - github, data.pr, repositoryName, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, + github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {pull_request: {head: {repo: {full_name: repositoryName}}}}}, "benhook1013", "FireMUD", require, data); } const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { "github.event_name": "pull_request", "github.repository": repositoryName, - "github.event.pull_request.number": 3390, "needs.image-meta.outputs.runtime_smoke_required": "true", + "github.event.pull_request.labels.*.name": ["canonical-play-transition"], + "needs.image-meta.outputs.runtime_smoke_required": "true", "steps.runtime-smoke.outcome": "failure", "steps.runtime-smoke.outputs.known_play_failure": "direct-backend-play-entitlement-unavailable-after-login", "steps.runtime-cleanup.outcome": "success", }; function markerAccepted(overrides = {}) { - let expression = markerExpression.replace("always()", "true"); + let expression = markerExpression.replace("always()", "true") + .replace("contains(", "includes("); for (const [key, value] of Object.entries({...markerValues, ...overrides})) { expression = expression.replaceAll(key, JSON.stringify(value)); } - return new Function(`return (${expression});`)(); + return new Function("includes", `return (${expression});`)((values, value) => values.includes(value)); } (async () => { assert.equal(markerAccepted(), true); @@ -3442,12 +3445,23 @@ function markerAccepted(overrides = {}) { {"steps.runtime-cleanup.outcome": "failure"}, {"steps.runtime-cleanup.outcome": "skipped"}, {"needs.image-meta.outputs.runtime_smoke_required": "false"}, - {"github.event.pull_request.number": 3391}, + {"github.event.pull_request.labels.*.name": []}, + {"github.repository": "attacker/FireMUD"}, {"github.event_name": "repository_dispatch"}, + {"github.event_name": "workflow_run"}, ]) assert.equal(markerAccepted(overrides), false); assert.equal(await verify(), true); + for (const stackPr of [3405, 3409, 3407, 3408, 3410]) { + assert.equal(await verify(d => {d.pr = String(stackPr); d.source.display_title = d.source.display_title.replace("pr-3390", `pr-${stackPr}`);}), true); + } for (const mutate of [ d => {d.pr = "3391";}, + d => {d.consumerRepository = "attacker/FireMUD";}, + d => {d.currentPullRequest.labels = [];}, + d => {d.currentPullRequest.labels = [{name: "other"}];}, + d => {d.currentPullRequest.state = "closed";}, + d => {d.currentPullRequest.head.sha = "d".repeat(40);}, + d => {d.currentPullRequest.base.ref = "main";}, d => {d.identity.baseSha = "d".repeat(40);}, d => {d.identity.headSha = "d".repeat(40);}, d => {d.identity.mergeSha = "d".repeat(40);}, @@ -3462,12 +3476,12 @@ function markerAccepted(overrides = {}) { d => {d.jobs.push({id: 2, status: "completed", conclusion: "failure"});}, d => {d.jobs[0].steps.push(step("Unrelated failure", "failure"));}, d => {d.jobs[0].steps.find(s => s.name === "Stop smoke stack").conclusion = "failure";}, - d => {d.jobs[0].steps.find(s => s.name.startsWith("Known PR")).conclusion = "skipped";}, - d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Known PR"));}, + d => {d.jobs[0].steps.find(s => s.name.startsWith("Known canonical transition")).conclusion = "skipped";}, + d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Known canonical transition"));}, d => {d.jobs[0].steps.find(s => s.name.startsWith("Export fixed")).conclusion = "success";}, d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Export fixed"));}, d => {d.source.conclusion = "success";}, ]) assert.equal(await verify(mutate), false, mutate.toString()); - console.log("Temporary PR 3390 PLAY exception positive and negative contracts passed."); + console.log("Canonical PLAY transition exception positive and negative contracts passed."); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE 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 bb96326833..5f2a0aa4a5 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 @@ -1762,9 +1762,7 @@ private DirectTextCallerContext directCaller(String request) { target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), - UUID.nameUUIDFromBytes( - ("session-" + account.getAccountUuid()).getBytes(StandardCharsets.UTF_8)) - .toString(), + "00042", request); } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java index 93461ec33c..7a6bea4f2a 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -169,7 +169,7 @@ static void exercise( target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), - transport.proxyConnectionId().toString(), + transport.transportSessionId(), UUID.randomUUID().toString()), new DirectTextJoinTarget( target.canonicalTenantId(), @@ -209,7 +209,7 @@ static void exercise( // Actual Account owner transition; caller binding is controlled and no World hold // spans this JOIN transaction. Reuse only the still-current verified LOGIN result. fixture.commitFirstJoin( - realmScope, UUID.randomUUID().toString(), transport.proxyConnectionId().toString()); + realmScope, UUID.randomUUID().toString(), transport.transportSessionId()); var joined = entitlementClient.read( lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); From 159326e255dd0fe3435b3e20c0e1dc9b3210156d Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 15:53:11 +1300 Subject: [PATCH 22/66] Clarify JOIN replay and classify verified scope mismatches --- ...CanonicalFirstJoinTerminalCoordinator.java | 3 +- .../service/impl/AccountServiceImpl.java | 16 ++- ...nicalFirstJoinTerminalCoordinatorTest.java | 18 +-- .../service/impl/AccountServiceImplTest.java | 104 +++++++++++++++++- 4 files changed, 121 insertions(+), 20 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index 5e7007c863..cd16e66977 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -145,7 +145,8 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( CanonicalJoinOperationEvidence operation = joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); requireExactOperation(operation, account.getId(), scope, requestId, callerBinding); - if ("COMMITTED".equals(operation.status()) || "FAILED".equals(operation.status())) { + // Definitive FAILED receipts are replayed by the adapter before policy evaluation. + if ("COMMITTED".equals(operation.status())) { return operation; } if (!"PENDING".equals(operation.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 b1fda10e97..47c49328ef 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 @@ -549,17 +549,23 @@ private PublishedRealmEvidence readCanonicalScopePublishedTarget( var resolved = Objects.requireNonNull( consumers.targets().resolvePublishedRealmAdmissionTarget(selector)); - net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec - .requireRetainedTargetMatches(selector, resolved.currentTarget()); + // Only a locally verified target mismatch is definitive. Exceptions from either remote + // owner (including malformed evidence) remain unavailable rather than condemning the intent. + try { + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .requireRetainedTargetMatches(selector, resolved.currentTarget()); + } catch (IllegalArgumentException mismatch) { + throw new AuthenticationException( + "CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE, mismatch); + } if (!selector.equals(resolved.selector())) - throw new IllegalStateException("Resolved selector differs"); + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); var published = Objects.requireNonNull( consumers.targets().readPublishedRealmAdmissionOwner(resolved.strictSelector())); if (!resolved.strictSelector().equals(published.selector()) || !resolved.currentTarget().equals(published.currentTarget())) { - throw new IllegalStateException( - "Published target differs from its resolved owner selectors"); + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } return published; } catch (AuthenticationException failure) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index 305c0855ff..adb293bc2a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -160,11 +160,10 @@ void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit(bo .commitCanonicalFirstJoin(REQUEST_ID, fixture.scope, CALLER_BINDING, fixture.expectedProof); } - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(strings = {"COMMITTED", "FAILED"}) - void terminalJoinReturnsStoredEvidenceWithoutReadingOrMutatingCurrentAuthority(String status) { + @Test + void committedJoinReturnsStoredEvidenceWithoutReadingOrMutatingCurrentAuthority() { Fixture fixture = new Fixture(); - var committed = Fixture.terminal(fixture.operation, fixture.expectedProof, status); + var committed = Fixture.terminal(fixture.operation, fixture.expectedProof, "COMMITTED"); when(fixture.accounts.findByAccountUuid(ACCOUNT_ID)).thenReturn(Optional.of(fixture.account)); when(fixture.operations.findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID)) .thenReturn(Optional.of(committed)); @@ -250,11 +249,12 @@ void inactiveJoinRestoresOnlyPlayerWithoutRegrantingRetainedElevatedRoles( null, null, null); - MembershipEvent restoredEvent = - MembershipAuthorityEventV1Codec.verify( - new String(fixture.event.payload(), StandardCharsets.UTF_8)); - assertThat(restoredEvent.roles()).containsExactly("player"); - assertThat(inactiveRoles.roles()).containsExactlyElementsOf(retainedRoles); + // Capture every role write, not the immutable fixture event returned by the mocked producer. + org.mockito.ArgumentCaptor> writtenRoles = + org.mockito.ArgumentCaptor.forClass(List.class); + verify(fixture.roles) + .replaceCanonical(any(), any(), any(), any(), anyLong(), writtenRoles.capture()); + assertThat(writtenRoles.getValue()).containsExactly("player"); } @org.junit.jupiter.params.ParameterizedTest 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 f09666822e..65ea432443 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 @@ -934,15 +934,22 @@ void canonicalJoinWithoutConsumerCompositionRefusesBeforeAccountIntentOrAuthorit retainedSubscriptionEvidenceRepository); } - @Test - void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMutation() { + @ParameterizedTest + @ValueSource( + strings = { + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "CONNECT_SCOPE_INVALID", + "REALM_UNAVAILABLE" + }) + void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMutation( + String outcome) { var f = canonicalJoinFixture(); when(f.pending.status()).thenReturn("FAILED"); - when(f.pending.outcome()).thenReturn("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + when(f.pending.outcome()).thenReturn(outcome); var result = f.browserJoin(); assertFalse(result.success()); assertTrue(result.replayed()); - assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", result.outcomeCode()); + assertEquals(outcome, result.outcomeCode()); verifyNoInteractions(f.sources, f.demos, f.hosting, f.observer, f.terminal); } @@ -1114,6 +1121,93 @@ void canonicalJoinChangedTargetBetweenStrictReadsIsTerminalWithoutMembershipEffe verifyNoInteractions(f.terminal); } + @ParameterizedTest + @ValueSource( + strings = {"retainedTarget", "resolvedSelector", "publishedSelector", "publishedTarget"}) + void canonicalJoinLocallyVerifiedTargetMismatchIsTerminal(String mismatch) { + var f = canonicalJoinFixture(); + if (mismatch.equals("retainedTarget") || mismatch.equals("resolvedSelector")) { + org.mockito.Mockito.doAnswer( + invocation -> { + var resolved = f.resolve(invocation.getArgument(0), f.target); + if (mismatch.equals("retainedTarget")) { + when(f.target.pointerVersion()).thenReturn(f.scope.pointerVersion() + 1L); + } else { + when(resolved.selector()) + .thenReturn( + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec + .RetainedTargetSelector.class)); + } + return resolved; + }) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + } else { + org.mockito.Mockito.doAnswer( + invocation -> { + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()) + .thenReturn( + mismatch.equals("publishedSelector") + ? org.mockito.Mockito.mock( + net.firedevops.firemud.common.world + .CanonicalGameplayRosterOwnerReadEvidence.Request.class) + : invocation.getArgument(0)); + when(published.currentTarget()) + .thenReturn( + mismatch.equals("publishedTarget") + ? org.mockito.Mockito.mock(Target.class) + : f.target); + return published; + }) + .when(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + } + + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, "CONNECT_SCOPE_MISMATCH"); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(f.terminal); + } + + @ParameterizedTest + @ValueSource(strings = {"resolver", "published"}) + void canonicalJoinRemoteValidationFailureRemainsRetryable(String owner) { + var f = canonicalJoinFixture(); + var failure = new IllegalArgumentException("Remote owner could not validate evidence"); + if (owner.equals("resolver")) { + org.mockito.Mockito.doThrow(failure) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + } else { + org.mockito.Mockito.doThrow(failure) + .when(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + } + var result = assertThrows(AuthenticationException.class, f::browserJoin); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.getCode()); + assertSame(failure, result.getCause()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"); + verifyNoInteractions(f.terminal); + } + @Test void canonicalJoinStrictPublishedSourceOutageCannotUseResolverOnlyAuthority() { var f = canonicalJoinFixture(); @@ -2064,7 +2158,7 @@ void canonicalBootstrapCharactersCannotDiscloseForAChangedRetainedTargetField(St default -> throw new AssertionError(field); } assertEquals( - "ADMISSION_POINTER_UNAVAILABLE", + "CONNECT_SCOPE_MISMATCH", assertThrows(AuthenticationException.class, f::characters).getCode()); verifyNoInteractions(f.roster); } From 38321b06c8fc354b5e94b9ef79e3e4565009a3be Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 16:14:53 +1300 Subject: [PATCH 23/66] Strengthen UUID mismatch proof and document preproduction boundary --- .../player-access-and-session.md | 2 ++ ...ountGameplayDelegationRedisIntegrationTest.java | 2 +- .../gamesession/client/AccountClientTest.java | 14 ++++++++++---- 3 files changed, 13 insertions(+), 5 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 65cb789794..40d045e66a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -20,6 +20,8 @@ The canonical Account boundary requires non-nil UUID tenant and game-instance id Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby remains unregistered; source custody, genuine cross-service scope/JOIN qualification and public admission remain unfinished. The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. +This is an intentionally breaking preproduction format cutover of the manually composed, currently unregistered lobby. No production rollback or migration compatibility is claimed. Numeric-era retained scope/JOIN bytes are not supported by the canonical UUID decoder; the existing SQL retention and exact-original identity guards remain unchanged. Repository inspection establishes no runtime registration and supplies no inventory of deployed rows. Existing-data verification belongs to future runtime wiring or activation, not a new merge gate or slicing requirement for this PR: before reusing any database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. If it does, preserve that evidence and resolve its retention and recovery requirements before invoking the new owner against it; neither this cutover nor the temporary CI exception authorizes deletion, identity rewriting or retention bypass. Fresh component fixtures do not prove historical compatibility. + ### Receiving review boundaries PR #3389 now carries the independent Account source/transport foundation on the supported `develop` runtime. Its unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery do not replace live PLAY authority. This draft PR #3390 retains canonical UUID schema retirement, the public facade/JOIN receiving cutover, initial hosting provider-write source with its focused units, and dependent physical proof; it remains unfinished until a functioning canonical PLAY replacement is qualified. PR #3403 retains private FRESH/World preparation. The source and prior corrections remain preserved through normal ancestry; the changed comparisons do not reset review counts or grant current coverage. No new caller custody, runtime registration, admission or activation is established by the reconstruction. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 22d0ca18e9..88edc2d1c8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -3114,7 +3114,7 @@ private static void commitPasswordResetAuthorityChange( logoutAllOperations, securityStateOperations, sourceChanges, - null, // connect scopes + null, // account audit outbox null, // join operations null, // email login challenges null, // realm grants 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 1035c9a6ff..f9ba16d98a 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 @@ -176,13 +176,15 @@ void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception var context = directTextContext(); for (var mismatched : List.of( - context.toBuilder().setTenantId("23").build(), + context.toBuilder().setTenantId("33333333-3333-4333-8333-333333333333").build(), context.toBuilder().setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce902").build(), context.toBuilder() .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328f") .build(), context.toBuilder().setPlayableStateScope("ISOLATED").build(), - context.toBuilder().setGameInstanceId("10").build())) { + context.toBuilder() + .setGameInstanceId("55555555-5555-4555-8555-555555555555") + .build())) { assertThat( client .issueDirectTextConnectScope(mismatched, directTextTarget()) @@ -526,7 +528,8 @@ void joinRejectsForeignOrMalformedSuccessfulIdentityWithoutRetry() throws Except assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("AUTH_UNAVAILABLE"); } - for (String tenant : List.of("", "tenant", "0", "23", " 22", "022")) { + for (String tenant : + List.of("", "tenant", "0", "23", " 22", "022", "33333333-3333-4333-8333-333333333333")) { when(fixture.initialStub().joinPublicProductionMembership(any())) .thenReturn(success.toBuilder().setTenantId(tenant).build()); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) @@ -604,7 +607,10 @@ void joinAlsoCorrelatesSuccessfulRetryBeforeReturningIt() throws Exception { when(fixture.initialStub().joinPublicProductionMembership(any())) .thenThrow(Status.UNAVAILABLE.asRuntimeException()); when(fixture.retryStub().joinPublicProductionMembership(any())) - .thenReturn(joinSuccess("JOINED", true).toBuilder().setTenantId("23").build()); + .thenReturn( + joinSuccess("JOINED", true).toBuilder() + .setTenantId("33333333-3333-4333-8333-333333333333") + .build()); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("AUTH_UNAVAILABLE"); From 62fae72dc4b6fbe01e79caa88beaf1975bd939d7 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 16:34:26 +1300 Subject: [PATCH 24/66] test(account): use numeric direct caller session fixture --- .../service/AccountCanonicalFirstJoinEventIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index 2c4ba8c520..af23d1f2b4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -671,7 +671,7 @@ void directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwner target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), - UUID.randomUUID().toString(), + "2001", requestId); var selected = new net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget( From ddb80ad6daa383e41f6903096be66cbf537454d3 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 17:15:09 +1300 Subject: [PATCH 25/66] docs(ci): qualify runtime proof under PLAY transition exception --- design/architecture/system-architecture-cicd.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 2e6793f53a..c25cd9bb55 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -76,7 +76,7 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s | Workflow | Execution context | Responsibility | What its GitHub run means | | --- | --- | --- | --- | -| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. The smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | +| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | | [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits keep the required `Smoke Gate` context but do not dispatch or cancel runtime construction; preservation follows [Required Gate Preservation](#required-gate-preservation), including an acknowledged supplementary pending barrier until matching substantive proof succeeds. | | [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) (`Publish PR Runtime Images`) | Trusted default-branch `workflow_run` or typed `repository_dispatch` definition | Verify the current PR and exact source artifact identity, then publish immutable `pr-merge-` tags in GHCR | GitHub displays the default branch because the trusted publisher runs there; its summary identifies the source PR run and base/head/merge SHAs. | | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | @@ -152,7 +152,7 @@ Other workflows support additional automation: - [`weekly-security-scan.yml`](../../.github/workflows/weekly-security-scan.yml) runs the weekly Trivy image scan. - [`ort-advisory.yml`](../../.github/workflows/ort-advisory.yml) runs the **Weekly ORT Advisory Scan**. - [`publish-base-image.yml`](../../.github/workflows/publish-base-image.yml) runs the **Weekly FireMUD Base Image Refresh** and is also the branch-guarded publication path for explicit base-image rebuilds on `develop` / `main`. -- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token. This proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. +- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token. A successful smoke run proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. The [temporary diagnostic exception](#pull-request-runtime-and-preview-chain) provides no passing `PLAY` or `LOOK` proof and permits no image publication. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. --- From e5016db404f0f043037e0665a47ab33be4b0b6d9 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 18:04:20 +1300 Subject: [PATCH 26/66] Fix hosted recovery findings and committed JOIN replay --- .github/scripts/classify-change-scope.cjs | 1 - .github/workflows/smoke.yml | 1 + dev-tools/tests/architecture-doc-contracts.sh | 6 +- .../pr-required-gate-context-contract.sh | 4 +- .../StripeHostingSubscriptionProvisioner.java | 93 +++++++++++++------ ...CanonicalFirstJoinTerminalCoordinator.java | 3 + .../service/impl/AccountServiceImpl.java | 30 ++++-- ...urceOwnerGuardPostgresIntegrationTest.java | 2 +- ...anonicalFirstJoinEventIntegrationTest.java | 43 +++++++++ ...ipeHostingSubscriptionProvisionerTest.java | 93 ++++++++++++++++++- ...nicalFirstJoinTerminalCoordinatorTest.java | 54 +++++++++++ 11 files changed, 287 insertions(+), 43 deletions(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index dff29ad5c8..ef6f8c01b1 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -174,7 +174,6 @@ function classifyChangeScope(inputFiles, options = {}) { (file) => !(file.startsWith("services/") && moduleForFile(file) !== null && - !isServiceSourceMarkdown(file) && isLightweightEligible(file)), ); const runAll = diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 6f9184f82e..1c86ae9a4b 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -797,6 +797,7 @@ jobs: ) return false; const expectedHeadRepository = context.payload.pull_request.head.repo?.full_name; if (typeof expectedHeadRepository !== "string" || + expectedHeadRepository !== repositoryName || source.head_repository?.full_name !== expectedHeadRepository) return false; if (source.head_sha !== identity.headSha) return false; const { data: workflow } = await withTransientGitHubRetry( diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 0c6f7b45b3..37a750bcab 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1015,8 +1015,10 @@ require_contains( "design/architecture/system-architecture-cicd.md", [ "builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token", - "This proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior", - "it does not establish successful public admission", + "Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission.", + "The diagnostic exception below provides no passing `PLAY` or `LOOK` proof.", + "image export and upload must be skipped", + "Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception;", "publish-pr-runtime-images.yml", "pr-merge-", "never checks out or executes PR source", diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 819f01e0c2..2d14445295 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3407,6 +3407,7 @@ const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; async function verify(mutate = () => {}) { const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, + eventHeadRepository: repositoryName, currentPullRequest: {state: "open", head: {sha: headSha}, base: {ref: "develop"}, labels: [{name: "canonical-play-transition"}]}, definition: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}); mutate(data); @@ -3418,7 +3419,7 @@ async function verify(mutate = () => {}) { `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), - {payload: {pull_request: {head: {repo: {full_name: repositoryName}}}}}, "benhook1013", "FireMUD", require, data); + {payload: {pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); } const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { @@ -3461,6 +3462,7 @@ function markerAccepted(overrides = {}) { d => {d.currentPullRequest.labels = [{name: "other"}];}, d => {d.currentPullRequest.state = "closed";}, d => {d.currentPullRequest.head.sha = "d".repeat(40);}, + d => {d.eventHeadRepository = "fork-owner/FireMUD"; d.source.head_repository.full_name = d.eventHeadRepository;}, d => {d.currentPullRequest.base.ref = "main";}, d => {d.identity.baseSha = "d".repeat(40);}, d => {d.identity.headSha = "d".repeat(40);}, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java index c6de43e0a2..f491949494 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java @@ -5,6 +5,7 @@ import com.stripe.model.Subscription; import com.stripe.net.RequestOptions; import com.stripe.param.SubscriptionCreateParams; +import com.stripe.param.SubscriptionListParams; import com.stripe.param.SubscriptionSearchParams; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Clock; @@ -21,6 +22,8 @@ * actor authorization, update/cancel command, runtime registration or entitlement is supplied. */ public final class StripeHostingSubscriptionProvisioner { + private static final long MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER = 100L; + private final com.stripe.StripeClient stripe; private final Clock clock; private final RequestOptions requestOptions; @@ -111,33 +114,71 @@ public Result provision(ProviderDispatch dispatch) { Subscription candidate; if (matches.getData().isEmpty()) { if (!dispatch.initialCallAllowed()) { - return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null); - } - if (!live(dispatch)) { - return new Pending("DISPATCH_LEASE_EXPIRED", null); + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + var listed = + stripe + .subscriptions() + .list( + SubscriptionListParams.builder() + .setCustomer(creation.providerCustomerId()) + .setStatus(SubscriptionListParams.Status.ALL) + .setLimit(MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) + .build(), + requestOptions); + if (listed == null + || listed.getData() == null + || !Boolean.FALSE.equals(listed.getHasMore()) + || listed.getData().size() > MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + candidate = null; + for (Subscription listedCandidate : listed.getData()) { + if (listedCandidate == null) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + if (metadata.equals(listedCandidate.getMetadata())) { + if (!creation.providerCustomerId().equals(listedCandidate.getCustomer())) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + if (candidate != null) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + candidate = listedCandidate; + } + } + if (candidate == null) { + return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null); + } + } else { + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + candidate = + stripe + .subscriptions() + .create( + SubscriptionCreateParams.builder() + .setCustomer(creation.providerCustomerId()) + .setDefaultPaymentMethod(dispatch.providerPaymentMethodId()) + .setCollectionMethod( + SubscriptionCreateParams.CollectionMethod.CHARGE_AUTOMATICALLY) + .setPaymentBehavior( + SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE) + .addItem( + SubscriptionCreateParams.Item.builder() + .setPrice(creation.planQuote().providerPriceId()) + .setQuantity(creation.planQuote().providerQuantity()) + .build()) + .putAllMetadata(metadata) + .build(), + requestOptions + .toBuilderFullCopy() + .setIdempotencyKey( + creation.subscriptionProvisioningRequestId().toString()) + .build()); } - candidate = - stripe - .subscriptions() - .create( - SubscriptionCreateParams.builder() - .setCustomer(creation.providerCustomerId()) - .setDefaultPaymentMethod(dispatch.providerPaymentMethodId()) - .setCollectionMethod( - SubscriptionCreateParams.CollectionMethod.CHARGE_AUTOMATICALLY) - .setPaymentBehavior( - SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE) - .addItem( - SubscriptionCreateParams.Item.builder() - .setPrice(creation.planQuote().providerPriceId()) - .setQuantity(creation.planQuote().providerQuantity()) - .build()) - .putAllMetadata(metadata) - .build(), - requestOptions - .toBuilderFullCopy() - .setIdempotencyKey(creation.subscriptionProvisioningRequestId().toString()) - .build()); } else { candidate = matches.getData().getFirst(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index cd16e66977..245397ad3f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -139,6 +139,9 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( ReadFence fence, StripeHostingSubscriptionObserver.Result observed) { requireWritableOwnerTransaction(); + Objects.requireNonNull(scope, "canonical JOIN scope is required"); + requireBoundedText(requestId, "canonical JOIN request ID"); + requireBoundedText(callerBinding, "verified caller binding"); Account account = accountRepository.findByAccountUuid(scope.accountId()).orElseThrow(); requireAccountIdentity(account, scope.accountId()); joinOperationRepository.lockAccount(account.getId()); 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 47c49328ef..6145d6e94a 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 @@ -662,8 +662,9 @@ private CanonicalJoinResult commitCanonicalJoin( allowPublicJoin = demo.allowPublicJoin(); entitlementVersion = demo.entitlementVersion(); } - accountJoinOperationRepository.bindCanonicalPolicyEvidence( - requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); + CanonicalJoinOperationEvidence policyBoundOperation = + accountJoinOperationRepository.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); Optional member = accountTenantMembershipRepository.findFreshMembershipForUpdate( scope.accountId(), scope.tenantId()); @@ -691,13 +692,24 @@ private CanonicalJoinResult commitCanonicalJoin( prepared.fence(), observation); requireCanonicalScopeFresh(consumers, scope); - var currentMembership = - accountTenantMembershipRepository - .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) - .orElseThrow(); - if (currentMembership.getMembershipVersion() + Optional currentMembership = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + if ("COMMITTED".equals(policyBoundOperation.status())) { + // A committed exact retry returns its original operation proof after the current + // policy check above. Membership may have changed since that proof was retained; + // expose only the current admission flag, never use the old proof as admission. + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + currentMembership + .map(AccountTenantMembership::isGameplayAdmissionAllowed) + .orElse(false)); + } + AccountTenantMembership committedMembership = currentMembership.orElseThrow(); + if (committedMembership.getMembershipVersion() != committed.terminalProof().membershipVersion() - || currentMembership.getMembershipAuthorityGeneration() + || committedMembership.getMembershipAuthorityGeneration() != committed.terminalProof().membershipAuthorityGeneration()) { throw new IllegalStateException( "Canonical JOIN result differs from current membership"); @@ -705,7 +717,7 @@ private CanonicalJoinResult commitCanonicalJoin( return new CanonicalJoinResult( committed.outcome(), committed.terminalProof(), - currentMembership.isGameplayAdmissionAllowed()); + committedMembership.isGameplayAdmissionAllowed()); })); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java index e00336b1cc..529cca5037 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -303,7 +303,7 @@ private AccountServiceImpl newPasswordResetService( logoutOperations, securityOperations, resetSourceChanges, - null, // connect scopes + null, // account audit outbox null, // join operations null, // email login challenges null, // realm grants diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index af23d1f2b4..b1c2734d0a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -657,6 +657,49 @@ void browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommitt assertThat(stored.scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid); } + @Test + void browserFacadeReplaysCommittedJoinProofAfterMembershipBecomesInactive() { + Fixture fixture = newFixture(); + BrowserFacade browser = fixture.browserFacade(); + var selected = + browser.service().listBootstrapRealms(browser.bootstrapToken(), "world").getFirst(); + String requestId = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), requestId); + + var original = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + fixture.seedControlledInactiveOwnerSnapshot(); + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + + assertThat(original.success()).isTrue(); + assertThat(original.outcomeCode()).isEqualTo("JOINED"); + assertThat(original.membershipVersion()).isEqualTo(2L); + assertThat(original.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(original.gameplayAdmissionAllowed()).isTrue(); + assertThat(replay.success()).isTrue(); + assertThat(replay.outcomeCode()).isEqualTo(original.outcomeCode()); + assertThat(replay.membershipId()).isEqualTo(original.membershipId()); + assertThat(replay.membershipVersion()).isEqualTo(original.membershipVersion()); + assertThat(replay.membershipAuthorityGeneration()) + .isEqualTo(original.membershipAuthorityGeneration()); + assertThat(replay.gameplayAdmissionAllowed()).isFalse(); + assertThat(replay.replayed()).isTrue(); + + var currentMembership = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + assertThat(currentMembership.getLifecycleState()).isEqualTo("INACTIVE"); + assertThat(currentMembership.getMembershipVersion()).isEqualTo(3L); + assertThat(currentMembership.getMembershipAuthorityGeneration()).isEqualTo(2L); + assertThat(currentMembership.isGameplayAdmissionAllowed()).isFalse(); + } + @Test void directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwners() { Fixture fixture = newFixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java index a64ef32f6d..17e160a886 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java @@ -107,15 +107,23 @@ void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() @Test void unknownOrExpiredIdempotencyOutcomeNeverAuthorizesAnotherCreate() { - Transport missing = transport(search("")); + Transport missing = transport(search(""), subscriptionList()); assertThat(adapter(missing).provision(dispatch(false))) .isEqualTo( new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); assertThat(missing.paths) .containsExactly( - "/v1/customers/cus_exact", "/v1/payment_methods/pm_exact", "/v1/subscriptions/search"); + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); assertThat(missing.methods) - .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + .containsExactly( + RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + assertThat(missing.params.get(3)) + .containsEntry("customer", "cus_exact") + .containsEntry("status", "all") + .containsEntry("limit", 100L); Transport lost = transport(search(""), subscription()); lost.failureAt = 3; lost.failure = mock(StripeException.class); @@ -146,6 +154,73 @@ void unknownOrExpiredIdempotencyOutcomeNeverAuthorizesAnotherCreate() { RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); } + @Test + void emptySearchUsesBoundedCustomerListOnlyForNonInitialLookup() { + Transport recovered = transport(search(""), subscriptionList(subscription()), subscription()); + var located = + (StripeHostingSubscriptionProvisioner.Located) + adapter(recovered).provision(dispatch(false)); + assertThat(located.providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(recovered.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions", + "/v1/subscriptions/sub_exact"); + assertThat(recovered.methods) + .containsExactly( + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET); + assertThat(recovered.params.get(3)) + .containsEntry("customer", "cus_exact") + .containsEntry("status", "all") + .containsEntry("limit", 100L); + + Transport incomplete = transport(search(""), subscriptionList(true, subscription())); + assertThat(adapter(incomplete).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); + assertThat(incomplete.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); + + Transport ambiguous = + transport(search(""), subscriptionList(subscription() + "," + subscription())); + assertThat(adapter(ambiguous).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); + assertThat(ambiguous.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); + + Transport wrongCustomer = + transport(search(""), subscriptionList(subscription().replace("cus_exact", "cus_other"))); + assertThat(adapter(wrongCustomer).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); + Transport wrongMetadata = + transport( + search(""), + subscriptionList( + subscription().replace(OPERATION.toString(), UUID.randomUUID().toString()))); + assertThat(adapter(wrongMetadata).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); + } + @Test void searchFailureDuplicatesAndIndependentBindingMismatchRemainNonterminal() { Transport failed = transport(search("")); @@ -325,6 +400,18 @@ private static String search(String objects) { return "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" + objects + "]}"; } + private static String subscriptionList(String... objects) { + return subscriptionList(false, objects); + } + + private static String subscriptionList(boolean hasMore, String... objects) { + return "{\"object\":\"list\",\"has_more\":" + + hasMore + + ",\"data\":[" + + String.join(",", objects) + + "]}"; + } + private static String subscription() { return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"cus_exact\",\"default_payment_method\":\"pm_exact\"," + "\"livemode\":false,\"status\":\"active\",\"cancel_at_period_end\":false,\"metadata\":{" diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index adb293bc2a..a395c0af0f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -188,6 +188,60 @@ void committedJoinReturnsStoredEvidenceWithoutReadingOrMutatingCurrentAuthority( fixture.eventProducer); } + @Test + void existingJoinRejectsNullScopeBeforeAnyOwnerRead() { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + null, REQUEST_ID, CALLER_BINDING, null, null, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("canonical JOIN scope is required"); + verifyNoInteractions( + fixture.accounts, + fixture.operations, + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + + @Test + void existingJoinRejectsUnboundedSelectorsBeforeAnyOwnerRead() { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + + for (String requestId : new String[] {null, "", " ", "x".repeat(129)}) { + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, requestId, CALLER_BINDING, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical JOIN request ID"); + } + for (String callerBinding : new String[] {null, "", " ", "x".repeat(129)}) { + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, callerBinding, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("verified caller binding"); + } + verifyNoInteractions( + fixture.accounts, + fixture.operations, + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) void inactiveJoinRestoresOnlyPlayerWithoutRegrantingRetainedElevatedRoles( From 9b2328aa635fe9df371001754262a9a94f04d6b0 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 19:13:56 +1300 Subject: [PATCH 27/66] Fix locked JOIN replay and strengthen current receiving proof --- .../player-access-and-session.md | 2 +- ...countMembershipAuthorityEventProducer.java | 12 ++- .../service/impl/AccountServiceImpl.java | 31 +++++-- ...iptionDispatchPostgresIntegrationTest.java | 32 ++++--- ...anonicalFirstJoinEventIntegrationTest.java | 88 +++++++++++++++++++ ...thorityEventProducerCanonicalJoinTest.java | 45 ++++++++++ .../service/impl/AccountServiceImplTest.java | 41 +++++++++ .../gamesession/client/AccountClient.java | 4 +- .../DirectTextAuthenticatedLobbyJoin.java | 1 - .../gamesession/client/AccountClientTest.java | 40 +++++++-- .../DirectTextAuthenticatedLobbyTest.java | 22 ++--- ...PlayerAdmissionEntitlementComposition.java | 26 +++++- ...ldPublishedAdmissionSourceComposition.java | 37 ++++++-- 13 files changed, 327 insertions(+), 54 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 40d045e66a..fb03ba1c2b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -905,7 +905,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token receiving currently fails closed before bootstrap/scope validation; current status and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and prepared explicit public-production JOIN (default receiving composition returns `AUTH_UNAVAILABLE`); canonical gameplay connect-token receiving currently fails closed before bootstrap/scope validation; current status and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) | Account REST/gRPC APIs, including prepared `/auth/bootstrap/join` and local JOIN RPC contracts (default receiving composition returns `AUTH_UNAVAILABLE`); `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, control-plane privilege claims, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and shared pod readiness currently fail closed pending canonical producer/replay/key qualification. The combined readiness hold withdraws both Gateway Service endpoint families; independent route-level Service readiness remains a pre-rollout gap. | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and deployment qualification in [Gateway readiness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness) | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index efa02ba2d0..8cb87334b2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -161,7 +161,17 @@ public Checkpoint publishCanonicalRestoredMembershipChange( Objects.requireNonNull(fence, "Original paid read fence required"); Objects.requireNonNull(observed, "Original sealed SDK result required"); } - var account = accountRepository.findByAccountUuid(scope.accountId()).orElseThrow(); + var account = + accountRepository + .findByAccountUuid(scope.accountId()) + .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); + if (account.getId() == null + || account.getId() <= 0L + || !scope.accountId().equals(account.getAccountUuid()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException("Canonical Account owner identity is contradictory"); + } joinOperationRepository.lockAccount(account.getId()); CanonicalJoinOperationEvidence operation = joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); 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 6145d6e94a..a6271795ce 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 @@ -637,8 +637,17 @@ private CanonicalJoinResult commitCanonicalJoin( status -> { lockCanonicalScopeAccount(scope); requireCanonicalScopeFresh(consumers, scope); - if ("FAILED".equals(prepared.operation().status())) { - return new CanonicalJoinResult(prepared.operation().outcome(), null, false); + CanonicalJoinOperationEvidence lockedOperation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(lockedOperation.status())) { + // Preparation precedes provider/target reads. Another exact attempt may have + // finished meanwhile, including before any policy evidence could be bound. + var retained = + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, lockedOperation.outcome()); + return new CanonicalJoinResult(retained.outcome(), null, false, true); } SourceSelection current = consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); @@ -675,11 +684,12 @@ private CanonicalJoinResult commitCanonicalJoin( gameplayAvailable ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" : "TENANT_BILLING_BLOCKED"; - if ("PENDING".equals(prepared.operation().status())) { + if ("PENDING".equals(policyBoundOperation.status())) { accountJoinOperationRepository.finishCanonicalFailure( requestId, scope, callerBinding, outcome); } - return new CanonicalJoinResult(outcome, null, false); + return new CanonicalJoinResult( + outcome, null, false, !"PENDING".equals(policyBoundOperation.status())); } var committed = consumers @@ -704,7 +714,8 @@ private CanonicalJoinResult commitCanonicalJoin( committed.terminalProof(), currentMembership .map(AccountTenantMembership::isGameplayAdmissionAllowed) - .orElse(false)); + .orElse(false), + true); } AccountTenantMembership committedMembership = currentMembership.orElseThrow(); if (committedMembership.getMembershipVersion() @@ -717,7 +728,8 @@ private CanonicalJoinResult commitCanonicalJoin( return new CanonicalJoinResult( committed.outcome(), committed.terminalProof(), - committedMembership.isGameplayAdmissionAllowed()); + committedMembership.isGameplayAdmissionAllowed(), + false); })); } @@ -748,7 +760,10 @@ private record CanonicalJoinPreparation( ReadFence fence) {} private record CanonicalJoinResult( - String outcome, CanonicalJoinTerminalProof proof, boolean gameplayAdmissionAllowed) {} + String outcome, + CanonicalJoinTerminalProof proof, + boolean gameplayAdmissionAllowed, + boolean replayed) {} /** Explicit non-admitting Entity projection; no default runtime client is registered here. */ public void setAccountBootstrapRosterReadClient(AccountBootstrapRosterReadClient client) { @@ -1075,7 +1090,7 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( proof == null ? 0L : proof.membershipVersion(), proof == null ? 0L : proof.membershipAuthorityGeneration(), committed.gameplayAdmissionAllowed(), - !"PENDING".equals(prepared.operation().status())); + committed.replayed()); } catch (AccountJoinOperationRepository.CanonicalJoinOperationConflictException failure) { throw new AuthenticationException( "IDEMPOTENCY_CONFLICT", "JOIN request ID conflicts", failure); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index 8f3d636e5a..69dfce3ab4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -445,22 +445,13 @@ void lostCreateResponseRecoversAfterTransientEmptySearchWithoutRecreating() { f.transport().emptySearchesRemaining = 1; f.clock().advance(Duration.ofSeconds(2)); var second = claim(f, first.subscriptionRowVersion()); - var delayed = - (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); - assertThat(delayed.disposition()).isEqualTo(Disposition.WAITING); - assertThat(delayed.providerResult()) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); - assertThat(f.transport().creates).isEqualTo(1); - f.clock().advance(Duration.ofSeconds(2)); - var third = claim(f, second.subscriptionRowVersion()); var result = (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(third, UUID.randomUUID(), UUID.randomUUID()); + service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); assertThat(f.transport().creates).isEqualTo(1); - assertThat(f.transport().searches).isEqualTo(3); + assertThat(f.transport().searches).isEqualTo(2); + assertThat(f.transport().lists).isEqualTo(1); assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isOne(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); } @@ -478,6 +469,7 @@ void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservati .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); assertThat(f.transport().exists).isTrue(); f.transport().emptySearchesRemaining = 2; + f.transport().emptyListsRemaining = 2; ProvisioningClaim previous = first; for (int attempt = 2; attempt <= 3; attempt++) { f.clock().advance(Duration.ofSeconds(2)); @@ -503,6 +495,7 @@ void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservati assertThat(retry.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); assertThat(retry.claim()).isNull(); assertThat(f.transport().searches).isEqualTo(3); + assertThat(f.transport().lists).isEqualTo(2); assertThat(f.transport().creates).isEqualTo(1); var current = Objects.requireNonNull( @@ -1059,7 +1052,9 @@ private static final class Transport implements StripeResponseGetter { private boolean loseCreateResponse; private Runnable duringCreate; private int emptySearchesRemaining; + private int emptyListsRemaining; private int searches; + private int lists; private int creates; private int subscriptionReads; @@ -1115,6 +1110,19 @@ public T request( "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" + (visible ? subscription() : "") + "]}"; + } else if ("/v1/subscriptions".equals(path) && method == RequestMethod.GET) { + lists++; + assertThat(params) + .containsEntry("customer", creation.providerCustomerId()) + .containsEntry("status", "all"); + boolean visible = exists && emptyListsRemaining == 0; + if (emptyListsRemaining > 0) { + emptyListsRemaining--; + } + response = + "{\"object\":\"list\",\"has_more\":false,\"data\":[" + + (visible ? subscription() : "") + + "]}"; } else if (path.equals("/v1/subscriptions") && method == RequestMethod.POST) { creates++; exists = true; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index b1c2734d0a..d1c6fea38a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -657,6 +657,94 @@ void browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommitt assertThat(stored.scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"COMMITTED", "FAILED_UNBOUND", "FAILED_BOUND"}) + void browserFacadeReplaysOperationFinishedAfterPreparation(String terminalState) { + Fixture fixture = newFixture(); + BrowserFacade browser = fixture.browserFacade(); + var selected = + browser.service().listBootstrapRealms(browser.bootstrapToken(), "world").getFirst(); + String requestId = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), requestId); + var callerReads = new java.util.concurrent.atomic.AtomicInteger(); + var retained = + new java.util.concurrent.atomic.AtomicReference< + AccountJoinOperationRepository.CanonicalJoinOperationEvidence>(); + org.mockito.Mockito.when( + browser + .sessions() + .isAccountSessionActive(fixture.account.getId(), browser.bootstrapToken())) + .thenAnswer( + invocation -> { + // The second caller read occurs outside SQL, after preparation and immediately before + // the final transaction. Finish another exact attempt in this deterministic gap. + if (callerReads.incrementAndGet() == 2) { + if ("COMMITTED".equals(terminalState)) { + var first = + browser.service().joinPublicProduction(browser.bootstrapToken(), request); + assertThat(first.success()).isTrue(); + assertThat(first.replayed()).isFalse(); + } else { + fixture.inTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + var scope = + fixture + .connectScopes + .findCanonical(selected.connectScopeId()) + .orElseThrow(); + var pending = + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + assertThat(pending.status()).isEqualTo("PENDING"); + if ("FAILED_BOUND".equals(terminalState)) { + var policy = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); + fixture.operations.bindCanonicalPolicyEvidence( + requestId, + scope, + pending.callerBinding(), + policy.allowPublicJoin(), + policy.entitlementVersion()); + } + fixture.operations.finishCanonicalFailure( + requestId, scope, pending.callerBinding(), "CONNECT_SCOPE_MISMATCH"); + return null; + }); + } + retained.set( + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow())); + } + return true; + }); + + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + + assertThat(retained.get()).isNotNull(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.success()).isEqualTo("COMMITTED".equals(terminalState)); + assertThat(replay.outcomeCode()).isEqualTo(retained.get().outcome()); + assertThat( + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow())) + .isEqualTo(retained.get()); + assertThat(fixture.countAll("account_audit_outbox")) + .isEqualTo("COMMITTED".equals(terminalState) ? 1L : 0L); + } + @Test void browserFacadeReplaysCommittedJoinProofAfterMembershipBecomesInactive() { Fixture fixture = newFixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index ad83ab5d25..237442cc7a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -114,6 +114,51 @@ void restoreRequiresCanonicalScopeBeforeReadingOwnerState() { fixture.verifyNoOwnerInteractions(); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"absent", "null-id", "zero-id", "wrong-uuid", "null-provenance", "source-id"}) + void restoreRejectsContradictoryAccountIdentityBeforeLocking(String malformed) { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + switch (malformed) { + case "null-id" -> fixture.account.setId(null); + case "zero-id" -> fixture.account.setId(0L); + case "wrong-uuid" -> fixture.account.setAccountUuid(UUID.randomUUID()); + case "null-provenance" -> fixture.account.setAccountUuidProvenance(null); + case "source-id" -> fixture.account.setAccountUuidSourceNumericId(99L); + default -> {} + } + when(fixture.accounts.findByAccountUuid(ACCOUNT_UUID)) + .thenReturn("absent".equals(malformed) ? Optional.empty() : Optional.of(fixture.account)); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.absenceBaseline, + null, + null, + null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "absent".equals(malformed) + ? "Canonical Account identity is absent" + : "Canonical Account owner identity is contradictory"); + + verifyNoInteractions( + fixture.joinOperations, + fixture.memberships, + fixture.roles, + fixture.pairs, + fixture.authority, + fixture.outbox, + fixture.sourceEvidence, + fixture.tenantAuthorityEvents, + fixture.entitlements); + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.CsvSource({ "request,null", 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 65ea432443..262780703c 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 @@ -892,6 +892,31 @@ void canonicalCommittedRetryRevalidatesCurrentPolicyBeforeReturningRetainedTermi .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalConcurrentCommitUsesLockedReplayStateAndStillChecksCurrentPolicy(boolean gameplay) { + var f = canonicalJoinFixture(); + when(f.committed.status()).thenReturn("COMMITTED"); + when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(f.requestId)) + .thenReturn(Optional.of(f.pending), Optional.of(f.committed)); + when(accountJoinOperationRepository.bindCanonicalPolicyEvidence( + f.requestId, f.scope, f.binding, true, 1L)) + .thenReturn(f.committed); + when(f.demo.gameplayAvailable()).thenReturn(gameplay); + + var result = f.browserJoin(); + + assertTrue(result.replayed()); + assertEquals(gameplay, result.success()); + assertEquals(gameplay ? "JOINED" : "TENANT_BILLING_BLOCKED", result.outcomeCode()); + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + if (!gameplay) verifyNoInteractions(f.terminal); + } + @Test void canonicalCommittedRetryCannotUseUnavailableCurrentEntitlementOrRewriteTerminalBytes() { var f = canonicalJoinFixture(); @@ -946,6 +971,9 @@ void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMut var f = canonicalJoinFixture(); when(f.pending.status()).thenReturn("FAILED"); when(f.pending.outcome()).thenReturn(outcome); + when(accountJoinOperationRepository.finishCanonicalFailure( + f.requestId, f.scope, f.binding, outcome)) + .thenReturn(f.pending); var result = f.browserJoin(); assertFalse(result.success()); assertTrue(result.replayed()); @@ -1392,6 +1420,9 @@ void canonicalDirectJoinUsesTheSameTerminalOwnerAndUuidTargetWithoutBootstrapSes var f = canonicalJoinFixture(); var caller = f.directCaller(f.requestId); f.binding = caller.sessionId(); + when(accountJoinOperationRepository.bindCanonicalPolicyEvidence( + f.requestId, f.scope, caller.sessionId(), true, 1L)) + .thenReturn(f.pending); org.mockito.Mockito.clearInvocations(sessionService); var result = canonicalGameSessionPeer() @@ -1402,7 +1433,10 @@ void canonicalDirectJoinUsesTheSameTerminalOwnerAndUuidTargetWithoutBootstrapSes new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); assertTrue(result.success()); assertEquals(f.scope.tenantId(), result.tenantId()); + assertFalse(result.replayed()); verifyNoInteractions(sessionService); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, caller.sessionId(), true, 1L); org.mockito.Mockito.verify(f.terminal) .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); } @@ -1649,6 +1683,13 @@ private CanonicalJoinFixture(String requestId) { when(pending.status()).thenReturn("PENDING"); when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId)) .thenReturn(Optional.of(pending)); + when(accountJoinOperationRepository.bindCanonicalPolicyEvidence( + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.eq(scope), + org.mockito.ArgumentMatchers.eq(binding), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.anyLong())) + .thenReturn(pending); when(sources.readCurrentSourceSelection(scope.tenantId())).thenReturn(source); when(source.kind()) .thenReturn( 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 c8741a5e58..968fa7e2c5 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 @@ -290,9 +290,7 @@ private JoinPublicProductionMembershipResponse correlateJoin( } if (response.getSuccess() && (!request.getPlayerContext().getAccountId().equals(response.getAccountId()) - || !request.getPlayerContext().getTenantId().equals(response.getTenantId()) - || "JOINED".equals(response.getOutcomeCode()) - && !response.getGameplayAdmissionAllowed())) { + || !request.getPlayerContext().getTenantId().equals(response.getTenantId()))) { return joinUnavailable(); } return response; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java index 4420a992ba..d23c662859 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java @@ -123,7 +123,6 @@ public static void requirePositiveReply( || reply.hasError() || !reply.getSuccess() || !Set.of("JOINED", "ALREADY_ACTIVE").contains(reply.getOutcomeCode()) - || "JOINED".equals(reply.getOutcomeCode()) && !reply.getGameplayAdmissionAllowed() || !scope.evidence().accountId().toString().equals(reply.getAccountId()) || !scope.issued().target().tenantId().equals(reply.getTenantId()) || !reply.getMembershipId().matches("[1-9][0-9]{0,18}") 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 f9ba16d98a..0653864b9c 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 @@ -169,6 +169,30 @@ void directTextMethodsRejectMissingAndMalformedCallerFieldsBeforeDispatch() thro org.mockito.Mockito.verifyNoInteractions(stub); } + @ParameterizedTest + @ValueSource( + strings = { + "abc", + "-1", + " 42", + "+1", + "0", + "000", + "000000000000000000000000000000001", + "9223372036854775808" + }) + void directTextMethodsRejectMalformedNumericSessionIdsBeforeDispatch(String sessionId) + throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var client = newClient(stub); + var context = directTextContext().toBuilder().setSessionId(sessionId).build(); + + assertThat(client.issueDirectTextConnectScope(context, directTextTarget()).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(join(client, context).getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + org.mockito.Mockito.verifyNoInteractions(stub); + } + @Test void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception { var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); @@ -435,16 +459,17 @@ void joinPreservesAlreadyActiveNonAdmittingReceipt() throws Exception { } @Test - void joinDoesNotAcceptJoinedOutcomeWithoutAdmissionFlag() throws Exception { + void joinPreservesJoinedNonAdmittingReplayReceipt() throws Exception { var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); - when(fixture.initialStub().joinPublicProductionMembership(any())) - .thenReturn( - joinSuccess("JOINED", false).toBuilder().setGameplayAdmissionAllowed(false).build()); + var expected = + joinSuccess("JOINED", true).toBuilder().setGameplayAdmissionAllowed(false).build(); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); var result = join(fixture.client(), directTextContext()); - assertThat(result.getSuccess()).isFalse(); - assertThat(result.getError().getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(result).isSameAs(expected); + assertThat(result.getGameplayAdmissionAllowed()).isFalse(); + assertThat(result.getReplayed()).isTrue(); verify(fixture.initialStub()).joinPublicProductionMembership(any()); verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); } @@ -546,7 +571,8 @@ void joinRetriesOnceWithSameImmutableRequestAfterChannelRebuild(String status) t var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); when(fixture.initialStub().joinPublicProductionMembership(any())) .thenThrow(Status.fromCode(Status.Code.valueOf(status)).asRuntimeException()); - var expected = joinSuccess("JOINED", true); + var expected = + joinSuccess("JOINED", true).toBuilder().setGameplayAdmissionAllowed(false).build(); when(fixture.retryStub().joinPublicProductionMembership(any())).thenReturn(expected); assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index ec33654ac1..28f884ee4e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -135,12 +135,13 @@ void positiveReplyPreservesTheFullPositiveAccountBigintBoundary() { .isEqualTo(response); } - @Test - void alreadyActiveNonAdmittingMembershipIsRetainedAsAnExactNonAdmissionReceipt() { + @ParameterizedTest + @ValueSource(strings = {"JOINED", "ALREADY_ACTIVE"}) + void nonAdmittingMembershipIsRetainedAsAnExactNonAdmissionReceipt(String outcome) { var f = new Fixture(); var response = positive().toBuilder() - .setOutcomeCode("ALREADY_ACTIVE") + .setOutcomeCode(outcome) .setGameplayAdmissionAllowed(false) .setMembershipVersion(8L) .setMembershipAuthorityGeneration(4L) @@ -152,16 +153,11 @@ void alreadyActiveNonAdmittingMembershipIsRetainedAsAnExactNonAdmissionReceipt() assertThat(response.getGameplayAdmissionAllowed()).isFalse(); assertThat(response.getMembershipVersion()).isEqualTo(8L); assertThat(response.getMembershipAuthorityGeneration()).isEqualTo(4L); - } - - @Test - void joinedReceiptCannotClaimSuccessWithoutGameplayAdmission() { - var f = new Fixture(); - var response = positive().toBuilder().setGameplayAdmissionAllowed(false).build(); - - assertThatThrownBy( - () -> DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) - .isInstanceOf(IllegalArgumentException.class); + var completed = + new DirectTextAuthenticatedLobbyJoin( + f.scope, f.frozen.request(), State.COMPLETED, Optional.of(response)); + assertThat(completed.reply()).contains(response); + assertThat(completed.reply().orElseThrow().getGameplayAdmissionAllowed()).isFalse(); } @Test diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java index 7a6bea4f2a..de8d567853 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -5,6 +5,8 @@ import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; @@ -34,6 +36,7 @@ import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginPhysicalCompositionFixture; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import net.firedevops.firemud.test.LoopbackMtlsTestPki; @@ -214,20 +217,39 @@ static void exercise( entitlementClient.read( lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); fixture.assertAdmittingEvidence(joined); + var journal = new InitialGameplayLoginCoordinationJournalRepository(gs); + var beforeCustodyRefusal = journal.readCommitted(coordinates).orElseThrow(); assertThatThrownBy( () -> entitlementClient.read( lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.CANCELLED); + assertThat(status.getDescription()) + .isEqualTo("Account player-admission entitlement read did not complete"); + }); + fixture.assertAdmittingEvidence(joined); + assertThat(login.evidence()).isEqualTo(evidence); + assertThat(journal.readCommitted(coordinates)).contains(beforeCustodyRefusal); assertThat(physicalLogin.abandonOriginalAfterCustodyLoss().status()) .isEqualTo( net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner .Status.ACCOUNT_RETIRED); + var beforeClosedResultRefusal = journal.readCommitted(coordinates).orElseThrow(); + // Cleanup has closed the private result. This proves local disposal refusal, + // not an Account-side retired-token read over the wire. assertThatThrownBy( () -> entitlementClient.read( lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Canonical LOGIN private result is closed"); + fixture.assertAdmittingEvidence(joined); + assertThat(login.evidence()).isEqualTo(evidence); + assertThat(journal.readCommitted(coordinates)).contains(beforeClosedResultRefusal); } catch (RuntimeException | Error failure) { failure.addSuppressed( new AssertionError( diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java index a1e9ed5ffb..96aa7331be 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -6,6 +6,8 @@ import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; @@ -15,6 +17,7 @@ import java.nio.file.Path; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; @@ -35,7 +38,6 @@ import net.firedevops.firemud.gamesession.repository.CanonicalPublishedAdmissionActualOwnerCompositionFixture; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.jooq.DSLContext; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Real GS OPEN/current publication and World ACTIVE reads over authenticated sockets, followed by @@ -110,15 +112,23 @@ static void exercise( .toList()); // This is the sole stipulated source: the exact published set already used by the real // preparation/OPEN owners. No Game Design issuing-owner proof is claimed here. + var policySourcePeerFailure = new AtomicReference(); var policySource = new PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase() { @Override public void listPublishedRealmEntryPolicies( ListPublishedRealmEntryPoliciesRequest request, StreamObserver observer) { - assertThat(GrpcPeerIdentity.current().uri()) - .isEqualTo(peer(namespace, "game-session-service")); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var authenticatedPeer = GrpcPeerIdentity.current(); + String expectedPeer = peer(namespace, "game-session-service"); + if (authenticatedPeer == null || !expectedPeer.equals(authenticatedPeer.uri())) { + policySourcePeerFailure.compareAndSet( + null, + "Expected authenticated peer " + + expectedPeer + + " but was " + + (authenticatedPeer == null ? "missing" : authenticatedPeer.uri())); + } observer.onNext( PublishedRealmEntryPolicyReadGrpcCodec.toResponse( PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(request), policies)); @@ -201,7 +211,17 @@ public void listPublishedRealmEntryPolicies( target.catalogRevision(), target.pointerVersion()); assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Canonical Game Session admission decision is unavailable"); + }); + var afterRefusal = accountClient.resolvePublishedRealmAdmissionTarget(selector); + assertThat(afterRefusal.selector()).isEqualTo(resolved.selector()); + assertThat(afterRefusal.currentTarget()).isEqualTo(resolved.currentTarget()); WorldPlayerAdmissionEntitlementComposition.exercise( root, originalAccount, @@ -217,7 +237,12 @@ public void listPublishedRealmEntryPolicies( } } } finally { - stop(design); + try { + stop(design); + } finally { + // Assert on the test thread, preserving peer diagnostics even if the caller failed. + assertThat(policySourcePeerFailure.get()).as("published policy source peer").isNull(); + } } } From 8d193b921fea09db26917a239d5f2da16a0289d5 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 19:14:31 +1300 Subject: [PATCH 28/66] Defer ancillary CI scope optimization to existing CI successor --- .github/scripts/classify-change-scope.cjs | 20 +--- .../scripts/classify-change-scope.test.cjs | 113 ------------------ design/project-management/ai-observations.md | 8 -- 3 files changed, 2 insertions(+), 139 deletions(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index ef6f8c01b1..02d5efe5e6 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -133,7 +133,6 @@ function isPythonDependency(file) { function isLightweightEligible(file) { return ( (isDocumentation(file) || isValidationPython(file)) && - !isServiceSourceMarkdown(file) && file !== "dev-tools/docs/generate-erd.sh" && !isRuntimeAuthority(file) && !SHARED_FILES.has(file) @@ -158,27 +157,12 @@ function moduleForFile(file) { return null; } -function isServiceSourceMarkdown(file) { - return file.startsWith("services/") && - moduleForFile(file) !== null && - /^services\/[^/]+\/src\/.*\.md$/.test(file); -} - function classifyChangeScope(inputFiles, options = {}) { const files = [...new Set(inputFiles)].sort(); const forceAll = options.forceAll === true; - // Known service documentation outside source sets retains docs proof without - // selecting runtime modules, including README files under shared common-* paths. - // Unknown services, source resources and non-lightweight inputs remain fail closed. - const moduleInputFiles = files.filter( - (file) => - !(file.startsWith("services/") && - moduleForFile(file) !== null && - isLightweightEligible(file)), - ); const runAll = forceAll || - moduleInputFiles.some( + files.some( (file) => SHARED_FILES.has(file) || (SHARED_PREFIXES.some((prefix) => file.startsWith(prefix)) && @@ -192,7 +176,7 @@ function classifyChangeScope(inputFiles, options = {}) { ALL_SERVICES.forEach((service) => affectedServices.add(service)); ALL_MODULES.forEach((module) => affectedModules.add(module)); } else { - for (const file of moduleInputFiles) { + for (const file of files) { const module = moduleForFile(file); if (module !== null) { affectedModules.add(module); diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 320a8eabff..5bd0855abc 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -41,119 +41,6 @@ test("documentation-only changes use the lightweight path", () => { assert.deepEqual(result.affectedServices, []); }); -test("known service and shared-module documentation selects no heavy module proof", async () => { - for (const module of ALL_MODULES.filter((module) => module !== "load-testing")) { - for (const path of [`services/${module}/README.md`, `services/${module}/design/README.md`]) { - const result = await classifyGithubFiles([path], 1); - - assert.equal(result.runAll, false, path); - assert.equal(result.lightweightOnly, true, path); - assert.equal(result.docsChanged, true, path); - assert.deepEqual(result.affectedModules, [], path); - assert.deepEqual(result.affectedServices, [], path); - assert.deepEqual(result.bootableModules, [], path); - } - } -}); - -test("Markdown packaged under known service source retains module proof", () => { - for (const [path, module, service] of [ - ["services/account-service/src/main/resources/content/README.md", "account-service", "account-service"], - ["services/account-service/src/test/resources/fixtures/README.md", "account-service", "account-service"], - ]) { - const result = classifyChangeScope([path]); - - assert.equal(result.runAll, false, path); - assert.equal(result.lightweightOnly, false, path); - assert.equal(result.docsChanged, true, path); - assert.deepEqual(result.affectedModules, [module], path); - assert.deepEqual(result.affectedServices, service ? [service] : [], path); - assert.deepEqual(result.bootableModules, service ? [service] : [], path); - } - - const sharedPath = "services/common-platform-core/src/main/resources/schema/README.md"; - const sharedResult = classifyChangeScope([sharedPath]); - assert.equal(sharedResult.runAll, true, sharedPath); - assert.equal(sharedResult.lightweightOnly, false, sharedPath); - assert.equal(sharedResult.docsChanged, true, sharedPath); - assert.deepEqual(sharedResult.affectedModules, ALL_MODULES, sharedPath); -}); - -test("service documentation does not add modules to a cumulative runtime diff", async () => { - const result = await classifyGithubFiles([ - "services/common-platform-core/README.md", - "services/world-management-service/README.md", - "services/account-service/src/main/java/example/Account.java", - ], 3); - - assert.equal(result.runAll, false); - assert.equal(result.lightweightOnly, false); - assert.equal(result.docsChanged, true); - assert.deepEqual(result.affectedModules, ["account-service"]); - assert.deepEqual(result.affectedServices, ["account-service"]); - assert.deepEqual(result.bootableModules, ["account-service"]); -}); - -test("service docs never suppress shared runtime, toolchain, or workflow inputs", () => { - for (const path of [ - "services/common-platform-core/src/main/java/example/Shared.java", - "gradle/libs.versions.toml", - "protos/account.proto", - ".github/workflows/ci.yml", - ]) { - const result = classifyChangeScope(["services/account-service/README.md", path]); - - assert.equal(result.runAll, true, path); - assert.equal(result.lightweightOnly, false, path); - assert.deepEqual(result.affectedModules, ALL_MODULES, path); - } -}); - -test("forced and incomplete service-documentation inventories retain complete proof", async () => { - const path = "services/common-platform-core/README.md"; - const forced = classifyChangeScope([path], { forceAll: true }); - assert.equal(forced.runAll, true); - assert.equal(forced.lightweightOnly, false); - assert.deepEqual(forced.affectedModules, ALL_MODULES); - - for (const count of [undefined, 2, "1"]) { - const result = await classifyGithubFiles([path], count); - assert.equal(result.runAll, true); - assert.equal(result.lightweightOnly, false); - assert.deepEqual(result.affectedModules, ALL_MODULES); - } - const malformed = await classifyGithubFiles([{ filename: path, previous_filename: "" }], 1); - assert.equal(malformed.runAll, true); - assert.deepEqual(malformed.affectedModules, ALL_MODULES); -}); - -test("unknown-service documentation still fails closed", async () => { - const result = await classifyGithubFiles(["services/unknown-service/README.md"], 1); - - assert.equal(result.runAll, true); - assert.deepEqual(result.affectedModules, ALL_MODULES); - assert.deepEqual(result.affectedServices, ALL_SERVICES); -}); - -test("renaming runtime inputs to service docs retains their old runtime selection", async () => { - for (const [previous, expectedModules, runAll] of [ - ["services/account-service/src/main/java/Account.java", ["account-service"], false], - ["services/game-session-service/src/main/java/Session.java", - ["game-session-service", "account-service"], false], - ["services/common-platform-core/src/main/java/Shared.java", ALL_MODULES, true], - ["services/unknown-service/src/main/java/Owner.java", ALL_MODULES, true], - ]) { - const result = await classifyGithubFiles([{ - filename: "services/account-service/README.md", - previous_filename: previous, - }], 1); - - assert.equal(result.runAll, runAll, previous); - assert.equal(result.lightweightOnly, false, previous); - assert.deepEqual(result.affectedModules, expectedModules, previous); - } -}); - test("ERD generation remains docs-affecting but never uses the lightweight path", () => { const result = classifyChangeScope(["dev-tools/docs/generate-erd.sh"]); diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 75cb8eca99..31af3e1766 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -33,7 +33,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-02` (Pacific/Auckland): SpotBugs crashed during Account authentication extraction. - A distinct local JVM failure occurred at 5:06:16am NZDT on 2 November during the 49-file Account authentication extraction: the Temurin 25.0.5+8 SpotBugs worker `2436948` crashed with `SIGSEGV` in `IndexSetIterator::advance_and_next` while C2 compiled `ValueRangeAnalysisFactory.analyze`. The wrapper returned exit 1 without an observed resource-drain stall. Root preserved the fatal and compiler-replay logs in R1430 and reported the occurrence to Overseer. This differs from the earlier Java 21 G1 daemon failure; a common cause is unproven. Next: retain the unchanged targeted SpotBugs retry outcome and compare exact JVM/frame evidence if it recurs; do not treat passing tests as completion of the failed static gate. - - Recurrence on 3 November: public receiving proof 346 crashed Temurin 25.0.5+8 worker `4180380` during `:common-platform-core:spotbugsTest` with `SIGSEGV` in `PhaseIdealLoop::build_loop_late`. Fatal and replay logs are retained privately in R1430/public-static proof 346 JVM and in the original worktree. That task joins the existing Game Session main SpotBugs proof 198/200 holds pending the Overseer JVM investigation; do not retry it or change JVM options, JDK or host without that investigation’s direction. Other selected enabled checks and documentation pass; the complete static gate remains unqualified. A common cause is unknown. - `2026-11-01` (Pacific/Auckland): Two different repository-network failures interrupted one unchanged CI image build. - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. @@ -56,13 +55,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-03` (Pacific/Auckland): Physical issuer retirement lost a fresh Redis connection before mutation. - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. -- `2026-11-03` (Pacific/Auckland): GitHub job-log connector closes transport during CI failure inspection. - - Repeated per-job connector requests failed with `Transport closed` for #3386 Validation and #3388 World/Python jobs while other metadata reads worked. One later #3388 per-job request succeeded during an active workflow, without explaining the failures; whole-run `gh run view --log` still refused before completion. Both #3389 Account jobs `125829036896` / `125829037055` recurred. Read-only per-job `gh api` log retrieval recovered their bytes into private files; any ANSI-capable retrieval must write directly to the private file rather than a terminal. Cause remains unknown. Next: preserve exact request/transport diagnostics on recurrence and repair the connector; do not rerun CI or replace controller operations to recover logs. - -- `2026-11-04` (Pacific/Auckland): Gameplay controller MCP writes intermittently wait or return transient service errors while the bound CLI remains usable. - - Several native-fix and acknowledgement calls exceeded the initial 30-second tool wait; an unsent `deadline_exceeded` fix attempt and an `overloaded` acknowledgement with unknown outcome were also returned. The acknowledgement request was `request_aca253fec2bd7085257f04174863e644`; retrying its exact key/body/binding through the existing Gameplay CLI recovered it. Doctor verified the same clean `1ef2b58` connection and worker identity. No profile switch, worker replacement or grant reset was used. - - Cause remains unknown. FireController stewardship should compare bound MCP/long-wait concurrency and service traces against CLI round trips, preserving the original requests and idempotency receipts. Continue supported exact-key recovery; a pending response alone does not justify duplicate writes or reviews. - - `2026-11-04` (Pacific/Auckland): FireController automatic Hosted selection can remain stuck without a child operation. - While qualifying #3386, two normal channel-front starts returned `review_busy` although Hosted operation discovery was empty. FireController Worker confirmed an original automatic selection had stayed in `selecting` since 11:36 UTC on 3 November without creating a review operation; childless selections were absent from operation discovery. The original selection and request key are retained, and no duplicate review, queue override or grant was issued. Next: FireController Worker is fixing selector recovery and discovery; verify the installed correction and the original selection’s recovery before treating Hosted progression as restored. From 9d74c3ecc61a75cc1d095e14ba684ba987baf8fc Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 20:03:56 +1300 Subject: [PATCH 29/66] Align Account fixture contracts and retain admission proof failures --- .../account-service/api-contracts.md | 12 +- .../account-service/runtime-and-data.md | 4 +- ...untRuntimeStubServerCompatibilityTest.java | 182 ++++++++++++++++-- .../test/AccountRuntimeStubServer.java | 60 +++--- ...ldPublishedAdmissionSourceCleanupTest.java | 112 +++++++++++ ...ldPublishedAdmissionSourceComposition.java | 23 +-- 6 files changed, 336 insertions(+), 57 deletions(-) create mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ca239a4178..28d1c68b46 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -107,7 +107,7 @@ An unreachable Game Session authority maps to `AUTH_UNAVAILABLE`; a reachable ma `gameplayAvailable` controls discovery visibility; `allowPublicJoin` does not. This pre-scope result contains only world slug and display name and creates no membership, JOIN, connect scope, or gameplay-admission authority. Public bootstrap discovery does not resolve private playtest realms or substitute for later target selection, current entitlement, membership, grant, or admission checks. -The manually composed `AccountCanonicalPublicRealmScopeOwner` uses the same public source collection for UUID-bearing V2 selector scopes. It rechecks Account identity, fresh tenant provenance, current membership and billing-head observations in short Account transactions, retains the exact signed scope preimage and verifies its immutable readback. Protected Game Session, registry and provider reads stay outside those transactions. Scope expiry follows the configured scope lifetime capped by the original verified bootstrap expiry; a later check cannot restamp an expired observation. Public visibility remains membership-independent, while current membership and `allowPublicJoin` are facts for subsequent fresh selection and JOIN checks. The scope grants neither membership repair nor gameplay admission. This source remains unregistered and separate from the existing numeric facade and private-realm path; its proof and receiving gaps are recorded in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). +The manually composed `AccountCanonicalPublicRealmScopeOwner` uses the same public source collection for UUID-bearing V2 selector scopes. It rechecks Account identity, fresh tenant provenance, current membership and billing-head observations in short Account transactions, retains the exact signed scope preimage and verifies its immutable readback. Protected Game Session, registry and provider reads stay outside those transactions. Scope expiry follows the configured scope lifetime capped by the original verified bootstrap expiry; a later check cannot restamp an expired observation. Public visibility remains membership-independent, while current membership and `allowPublicJoin` are facts for subsequent fresh selection and JOIN checks. The scope grants neither membership repair nor gameplay admission. This source is manually composed by the public UUID facades but remains unregistered and separate from the private-realm path; its proof and receiving gaps are recorded in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). ### Account-Owned Safety Restriction Contract @@ -151,7 +151,11 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call. The Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. With canonical scope consumers absent, current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When consumers are manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/grant/pointer reads, token minting, or replay/session mutation. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. 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 obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain 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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call. The Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. With canonical scope consumers absent, current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When consumers are manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/grant/pointer reads, token minting, or replay/session mutation. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. 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 obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. + +### Account Tenant Identifier Boundary + +Public bootstrap realm projections (`BootstrapRealmDto`), direct-text caller/target scopes (`DirectTextCallerContext` and `DirectTextJoinTarget`), and explicit public-production JOIN results (`JoinPublicProductionResult` and `JoinPublicProductionMembershipResponse.tenant_id`) carry the canonical non-nil tenant UUID. Bootstrap realm and direct-text target game-instance identifiers likewise carry canonical non-nil UUIDs. The legacy runtime membership, entitlement and realm-grant reads still use the numeric tenant ID, including `GetTenantMembershipForRuntimeResponse.tenant_id`; the legacy Account tenant-export selector also remains numeric. These representations are specific to their contracts and must not be interchanged or inferred from Account UUID identity. Canonical facade inputs do not establish default runtime wiring or gameplay admission. ### Account UUID Response and REST Selector Identity @@ -161,7 +165,7 @@ The implemented legacy profile REST handlers and five global Account REST handle First-party bootstrap character discovery sends the authenticated bootstrap context's canonical Account UUID to Entity Management; Account's private storage key remains local. Entity's [ordinary ownership contract](../entity-management-service/api-contracts.md#ordinary-account-ownership) owns the receiver's same-namespace workload authorization and UUID-selected roster predicates. -The final ordinary receiving composition carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Profile `SessionContext` self-binding and global REST caller proof use that same UUID identity. Tenant identifiers remain numeric. Full token-profile/registry qualification, canonical tenant-scoped profile routes, complete portable or tenant-wide exports, production credential custody, public JOIN exposure and gameplay activation remain unqualified. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). +The final ordinary receiving composition carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Profile `SessionContext` self-binding and global REST caller proof use that same UUID identity. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification, canonical tenant-scoped profile routes, complete portable or tenant-wide exports, production credential custody, public JOIN exposure and gameplay activation remain unqualified. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). ### Tenant-Creation Current Authorization Read @@ -339,7 +343,7 @@ The disabled `ExportAccount`, `ExportTenantData`, `LinkExternalAccount`, `Reques ## REST APIs -Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant identifiers retain their existing representation. The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. +Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. | Method | Path | Description | | --- | --- | --- | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 12623d04c1..123f63a387 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,7 +16,7 @@ The `player-bootstrap` credential/result profile uses the persisted Account UUID Ordinary control-UI, gameplay password/email-OTP, and player-bootstrap issuance checks the authenticated Account's persisted UUID provenance and source-row identity and resolves that UUID back to the same Account row before consuming a successful challenge, signing, or storing a session. Successful ordinary authentication results and Account-issued JWT subject/Account claims carry that UUID. Identity readback failures use `AUTH_UNAVAILABLE`; invalid credentials retain their existing response. The final ordinary receiving qualification and its limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers; tenant storage selectors retain their numeric representation. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate. +The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers. Tenant representations follow the [Account tenant identifier boundary](./api-contracts.md#account-tenant-identifier-boundary), which distinguishes canonical public/direct-text scopes and JOIN results from legacy numeric runtime reads. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate. The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details. @@ -54,7 +54,7 @@ The source preparation also includes unregistered, caller-transaction-bound crea Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. -Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST exposes that UUID through `AccountDto.id`, while registration gRPC exposes it through `CreateAccountResponse.account_id`; the Account component of current Account/profile-local and legacy tenant exports also carries the UUID. The mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Tenant IDs and profile tenant identifiers retain their current representation. The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. +Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST exposes that UUID through `AccountDto.id`, while registration gRPC exposes it through `CreateAccountResponse.account_id`; the Account component of current Account/profile-local and legacy tenant exports also carries the UUID. The mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Profile tenant identifiers remain numeric; other tenant representations follow the [Account tenant identifier boundary](./api-contracts.md#account-tenant-identifier-boundary). The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 830a181fec..bdda13d502 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -22,6 +22,8 @@ import org.junit.jupiter.params.provider.ValueSource; class AccountRuntimeStubServerCompatibilityTest { + private static final String TENANT_ID = "5c03483e-d14c-4dc4-806e-297cdd209612"; + private static final String GAME_INSTANCE_ID = "fceab4e7-2922-4e6f-a4f4-dbaab3e25875"; private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; private static final String NAMESPACE_ID = "2ea958e0-13a2-41d0-9c39-59a96cf31412"; private static final Set NON_RUNTIME_METHODS = @@ -101,10 +103,10 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(accountUuid) - .setTenantId("11") + .setTenantId(TENANT_ID) .setRealmId(REALM_ID) - .setGameInstanceId("33") - .setSessionId("session-1") + .setGameInstanceId(GAME_INSTANCE_ID) + .setSessionId("1") .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") .setRequestId("join-request-1") @@ -113,13 +115,13 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe stub.issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId("11") + .setTenantId(TENANT_ID) .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") - .setGameInstanceId("33") + .setGameInstanceId(GAME_INSTANCE_ID) .setCatalogRevision(1L) .setPointerVersion(1L) .build()); @@ -184,6 +186,18 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro .setPlayerContext( validRequest.getPlayerContext().toBuilder().setRequestId(" ")) .build(), + validRequest.toBuilder() + .setPlayableStateScope("PRIVATE") + .setPlayerContext( + validRequest.getPlayerContext().toBuilder() + .setPlayableStateScope("PRIVATE")) + .build(), + validRequest.toBuilder().setWorldSlug("w".repeat(129)).build(), + validRequest.toBuilder().setRealmSlug("r".repeat(129)).build(), + validRequest.toBuilder() + .setPlayerContext( + validRequest.getPlayerContext().toBuilder().setRequestId("r".repeat(129))) + .build(), validRequest.toBuilder().setCatalogRevision(0L).build(), validRequest.toBuilder().setPointerVersion(-1L).build()); @@ -198,6 +212,145 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro } } + @ParameterizedTest + @ValueSource( + strings = { + "11", "00000000-0000-0000-0000-000000000000", + "5C03483E-D14C-4DC4-806E-297CDD209612", "1-1-1-1-1" + }) + void directTextScopeAndJoinRejectNoncanonicalTargetIds(String invalidId) throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = validConnectScopeRequest(accountUuid); + var caller = request.getPlayerContext(); + var invalidRequests = + List.of( + request.toBuilder() + .setTenantId(invalidId) + .setPlayerContext(caller.toBuilder().setTenantId(invalidId)) + .build(), + request.toBuilder() + .setRealmId(invalidId) + .setPlayerContext(caller.toBuilder().setRealmId(invalidId)) + .build(), + request.toBuilder() + .setGameInstanceId(invalidId) + .setPlayerContext(caller.toBuilder().setGameInstanceId(invalidId)) + .build(), + request.toBuilder() + .setPlayableStateNamespaceId(invalidId) + .setPlayerContext(caller.toBuilder().setPlayableStateNamespaceId(invalidId)) + .build()); + var join = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(caller) + .setConnectScopeId(stub.issueDirectTextConnectScope(request).getConnectScopeId()) + .setRequestId(caller.getRequestId()) + .build(); + assertThat(stub.joinPublicProductionMembership(join).getSuccess()).isTrue(); + for (var invalidRequest : invalidRequests) { + var scope = stub.issueDirectTextConnectScope(invalidRequest); + assertThat(scope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(scope.getConnectScopeId()).isEmpty(); + var replay = + stub.joinPublicProductionMembership( + join.toBuilder().setPlayerContext(invalidRequest.getPlayerContext()).build()); + assertThat(replay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(replay.getSuccess()).isFalse(); + assertThat(replay.getReplayed()).isFalse(); + } + } finally { + channel.shutdownNow(); + } + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + " ", + "session-1", + "0", + "-1", + "+1", + "1.0", + "9223372036854775808", + "00000000000000000000000000000000100" + }) + void directTextScopeAndJoinRejectInvalidTransportSessionsBeforeReplay(String session) + throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = + validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); + var invalidCaller = request.getPlayerContext().toBuilder().setSessionId(session).build(); + var invalidScope = + stub.issueDirectTextConnectScope( + request.toBuilder().setPlayerContext(invalidCaller).build()); + assertThat(invalidScope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(invalidScope.getConnectScopeId()).isEmpty(); + var join = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(request.getPlayerContext()) + .setConnectScopeId(stub.issueDirectTextConnectScope(request).getConnectScopeId()) + .setRequestId(request.getPlayerContext().getRequestId()) + .build(); + var invalidJoin = join.toBuilder().setPlayerContext(invalidCaller).build(); + assertThat(stub.joinPublicProductionMembership(invalidJoin).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(stub.joinPublicProductionMembership(join).getSuccess()).isTrue(); + var replay = stub.joinPublicProductionMembership(invalidJoin); + assertThat(replay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(replay.getSuccess()).isFalse(); + assertThat(replay.getReplayed()).isFalse(); + } finally { + channel.shutdownNow(); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"1", "0001", "9223372036854775807", "00000000000000000000000000000001"}) + void directTextScopeAndJoinAcceptAccountTransportSessionRange(String session) throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = + validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); + request = + request.toBuilder() + .setPlayerContext(request.getPlayerContext().toBuilder().setSessionId(session)) + .build(); + var scope = stub.issueDirectTextConnectScope(request); + assertThat(scope.getError().getCode()).isEmpty(); + var join = + stub.joinPublicProductionMembership( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(request.getPlayerContext()) + .setConnectScopeId(scope.getConnectScopeId()) + .setRequestId(request.getPlayerContext().getRequestId()) + .build()); + assertThat(join.getSuccess()).isTrue(); + assertThat(join.getTenantId()).isEqualTo(TENANT_ID); + } finally { + channel.shutdownNow(); + } + } + } + @Test void joinRequiresCallerSessionBeforeReplayAndResetClearsRetainedScopesAndOutcomes() throws Exception { @@ -429,15 +582,16 @@ void retainedJoinRejectsConflictingCallerAndScopeIdentity() throws Exception { validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(9L)); var otherTenantScope = scopeRequest.toBuilder() - .setTenantId("22") - .setPlayerContext(scopeRequest.getPlayerContext().toBuilder().setTenantId("22")) + .setTenantId("024c8a59-d3ee-4f64-8276-c4c43a2efe7f") + .setPlayerContext( + scopeRequest.getPlayerContext().toBuilder() + .setTenantId("024c8a59-d3ee-4f64-8276-c4c43a2efe7f")) .build(); var sameScopeNewId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); var conflicts = List.of( request.toBuilder() - .setPlayerContext( - request.getPlayerContext().toBuilder().setSessionId("session-2")) + .setPlayerContext(request.getPlayerContext().toBuilder().setSessionId("2")) .build(), request.toBuilder().setConnectScopeId(sameScopeNewId).build(), request.toBuilder() @@ -516,23 +670,23 @@ private static IssueDirectTextConnectScopeRequest validConnectScopeRequest(Strin PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(accountUuid) - .setTenantId("11") + .setTenantId(TENANT_ID) .setRealmId(REALM_ID) - .setGameInstanceId("33") - .setSessionId("session-1") + .setGameInstanceId(GAME_INSTANCE_ID) + .setSessionId("1") .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") .setRequestId("join-request-1") .build(); return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId("11") + .setTenantId(TENANT_ID) .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") - .setGameInstanceId("33") + .setGameInstanceId(GAME_INSTANCE_ID) .setCatalogRevision(1L) .setPointerVersion(1L) .build(); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index d76edbe563..2cf619a1f4 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -269,27 +269,11 @@ public void issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); - if (caller.getAccountId().isBlank() - || resolveRegisteredAccountId(caller.getAccountId()) == null - || caller.getTenantId().isBlank() - || caller.getRealmId().isBlank() - || caller.getRequestId().isBlank() - || caller.getGameInstanceId().isBlank() - || caller.getPlayableStateNamespaceId().isBlank() - || caller.getPlayableStateScope().isBlank() - || request.getTenantId().isBlank() - || request.getRealmId().isBlank() - || request.getGameInstanceId().isBlank() - || request.getWorldSlug().isBlank() - || request.getRealmSlug().isBlank() - || request.getPlayableStateNamespaceId().isBlank() - || request.getPlayableStateScope().isBlank() + if (!isValidDirectTextCaller(caller) + || !isBoundedText(request.getWorldSlug(), 128) + || !isBoundedText(request.getRealmSlug(), 128) || request.getCatalogRevision() <= 0 || request.getPointerVersion() <= 0 - || !isCanonicalUuid(caller.getRealmId()) - || !isCanonicalUuid(request.getRealmId()) - || !isCanonicalUuid(caller.getPlayableStateNamespaceId()) - || !isCanonicalUuid(request.getPlayableStateNamespaceId()) || !caller.getTenantId().equals(request.getTenantId()) || !caller.getRealmId().equals(request.getRealmId()) || !caller.getGameInstanceId().equals(request.getGameInstanceId()) @@ -331,25 +315,49 @@ private static boolean isCanonicalUuid(String value) { return false; } try { - return UUID.fromString(value).toString().equals(value); + UUID parsed = UUID.fromString(value); + return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); } catch (IllegalArgumentException ex) { return false; } } + private boolean isValidDirectTextCaller(PlayerExecutionContext caller) { + return resolveRegisteredAccountId(caller.getAccountId()) != null + && isCanonicalUuid(caller.getTenantId()) + && isCanonicalUuid(caller.getRealmId()) + && isCanonicalUuid(caller.getGameInstanceId()) + && isCanonicalUuid(caller.getPlayableStateNamespaceId()) + && Set.of("SHARED", "ISOLATED").contains(caller.getPlayableStateScope()) + && isPositiveTransportSession(caller.getSessionId()) + && isBoundedText(caller.getRequestId(), 128); + } + + private static boolean isPositiveTransportSession(String value) { + if (value.length() > 32 || !value.matches("[0-9]+")) { + return false; + } + try { + return Long.parseLong(value) > 0; + } catch (NumberFormatException ex) { + return false; + } + } + + private static boolean isBoundedText(String value, int maximumLength) { + return !value.isBlank() && value.length() <= maximumLength; + } + @Override public synchronized void joinPublicProductionMembership( JoinPublicProductionMembershipRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); StubConnectScope scope = connectScopesById.get(request.getConnectScopeId()); - if (request.getConnectScopeId().isBlank() - || request.getRequestId().isBlank() + if (!isBoundedText(request.getConnectScopeId(), 2048) + || !isBoundedText(request.getRequestId(), 128) || !request.getRequestId().equals(caller.getRequestId()) - || caller.getAccountId().isBlank() - || resolveRegisteredAccountId(caller.getAccountId()) == null - || caller.getTenantId().isBlank() - || caller.getSessionId().isBlank() + || !isValidDirectTextCaller(caller) || scope == null || !scope.expiresAt().isAfter(clock.instant()) || !scope.accountId().equals(caller.getAccountId()) diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java new file mode 100644 index 0000000000..836920793e --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class WorldPublishedAdmissionSourceCleanupTest { + @Test + void successfulBodyStopsServerAndChecksLatePeerDiagnostic() throws Exception { + var server = stoppedServer(); + var peer = new AtomicReference(); + Throwable result = + catchThrowable( + () -> { + try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); + var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { + peer.set("wrong authenticated peer"); + } + }); + + assertThat(result) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("wrong authenticated peer"); + verify(server).shutdownNow(); + verify(server).awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + void primaryFailureRetainsPeerDiagnostic() throws Exception { + var server = stoppedServer(); + var primary = new AssertionError("admission failed"); + Throwable result = run(server, "wrong authenticated peer", primary); + + assertThat(result).isSameAs(primary); + assertThat(result.getSuppressed()).hasSize(1); + assertThat(result.getSuppressed()[0]) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("published policy source peer") + .hasMessageContaining("wrong authenticated peer"); + } + + @Test + void primaryFailureRetainsCleanupFailureAndPeerDiagnostic() throws Exception { + var server = stoppedServer(); + var cleanup = new InterruptedException("cleanup interrupted"); + when(server.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(cleanup); + var primary = new AssertionError("admission failed"); + Throwable result = run(server, "wrong authenticated peer", primary); + + assertThat(result).isSameAs(primary); + assertThat(result.getSuppressed()).hasSize(2); + assertThat(result.getSuppressed()[0]).isSameAs(cleanup); + assertThat(result.getSuppressed()[1]).hasMessageContaining("wrong authenticated peer"); + } + + @Test + void cleanupFailureRemainsPrimaryWhenBodySucceeds() throws Exception { + var server = stoppedServer(); + var cleanup = new IllegalStateException("shutdown failed"); + when(server.shutdownNow()).thenThrow(cleanup); + Throwable result = run(server, "wrong authenticated peer", null); + + assertThat(result).isSameAs(cleanup); + assertThat(result.getSuppressed()).hasSize(1); + assertThat(result.getSuppressed()[0]).hasMessageContaining("wrong authenticated peer"); + } + + @Test + void unsuccessfulTerminationCannotReplacePrimaryFailure() throws Exception { + var server = stoppedServer(); + when(server.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); + var primary = new AssertionError("admission failed"); + Throwable result = run(server, null, primary); + + assertThat(result).isSameAs(primary); + assertThat(result.getSuppressed()).singleElement().isInstanceOf(AssertionError.class); + } + + @Test + void successfulBodyAndCleanupDoNotFail() throws Exception { + var server = stoppedServer(); + assertThat(run(server, null, null)).isNull(); + verify(server).shutdownNow(); + verify(server).awaitTermination(5, TimeUnit.SECONDS); + } + + private static Server stoppedServer() throws InterruptedException { + var server = mock(Server.class); + when(server.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + return server; + } + + private static Throwable run(Server server, String peerFailure, AssertionError primary) { + var peer = new AtomicReference<>(peerFailure); + return catchThrowable( + () -> { + try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); + var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { + if (primary != null) { + throw primary; + } + } + }); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java index 96aa7331be..6d66e9b778 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -136,7 +136,9 @@ public void listPublishedRealmEntryPolicies( } }; Server design = server(pki, "design", policySource); - try { + // Reverse close order retains shutdown and peer diagnostics as suppressed failures. + try (var peerCheck = checkPeerOnClose(policySourcePeerFailure); + var designLifetime = stopOnClose(design)) { var endpoints = new ServiceEndpointsProperties(); endpoints.setGameDesignService("localhost:" + design.getPort()); var channels = new GrpcChannelFactory(); @@ -157,7 +159,7 @@ public void listPublishedRealmEntryPolicies( "gs-server", CanonicalPublishedAdmissionActualOwnerCompositionFixture.receiver( gs, namespace, policyClient, worldClient)); - try { + try (var receiverLifetime = stopOnClose(receiver)) { endpoints.setGameSessionService("localhost:" + receiver.getPort()); try (var accountClient = new CanonicalGameplayAdmissionDecisionReadClient( @@ -232,20 +234,19 @@ public void listPublishedRealmEntryPolicies( redisHost, redisPort); } - } finally { - stop(receiver); } } - } finally { - try { - stop(design); - } finally { - // Assert on the test thread, preserving peer diagnostics even if the caller failed. - assertThat(policySourcePeerFailure.get()).as("published policy source peer").isNull(); - } } } + static AutoCloseable checkPeerOnClose(AtomicReference peerFailure) { + return () -> assertThat(peerFailure.get()).as("published policy source peer").isNull(); + } + + static AutoCloseable stopOnClose(Server server) { + return () -> stop(server); + } + private static String peer(String namespace, String service) { return "spiffe://firemud/ns/" + namespace + "/sa/" + service; } From 2431ce393e881d067267afe44c77f1876d7efef6 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 20:46:34 +1300 Subject: [PATCH 30/66] fix(account): replay failed canonical joins without remote reads --- .../player-access-and-session.md | 2 +- .../service/impl/AccountServiceImpl.java | 20 +++++---- ...titlementOwnerPostgresIntegrationTest.java | 2 +- .../service/impl/AccountServiceImplTest.java | 45 ++++++++++++++++++- 4 files changed, 58 insertions(+), 11 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 fb03ba1c2b..f17e8c1db1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ Account initial/current/final creation owners, explicit initial billing-owner co ### Temporary canonical PLAY transition exception -The existing canonical-cutover stack may opt into the [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) with the `canonical-play-transition` label. The source event and live PR must both have it. This includes #3390 and, only if deliberately labeled, dependent #3405, #3409, #3407, #3408 and #3410; #3403 is not approved for the exception. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. +The existing canonical-cutover stack may opt into the [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) with the `canonical-play-transition` label. The source event and live PR must both have it. This includes #3390 and, only if deliberately labeled, dependent #3405, #3409, #3407, #3408 and #3410; #3403 is not approved for the exception and must remain unlabeled. This PR list records the approved operational scope, not a workflow PR-number allowlist: applying the label is the workflow scope control, and maintainers must limit it to these approved cuts. The workflow independently checks repository, event, exact PR tuple, classified failure, qualification and cleanup. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. ### Direct-text scope and JOIN identifier cutover 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 a6271795ce..56baf5a251 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 @@ -1066,15 +1066,19 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( try { CanonicalJoinPreparation prepared = prepareCanonicalJoin(consumers, scope, request.requestId(), callerBinding); - Target target = readCanonicalScopeTarget(consumers, scope); - // The SDK's sealed result crosses source transactions; provider I/O never runs under SQL. - StripeHostingSubscriptionObserver.Result observation = - prepared.fence() == null - ? null - : consumers.observer().observe(prepared.fence().binding()); - if (!target.equals(readCanonicalScopeTarget(consumers, scope))) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + StripeHostingSubscriptionObserver.Result observation = null; + if (!"FAILED".equals(prepared.operation().status())) { + Target target = readCanonicalScopeTarget(consumers, scope); + // The SDK's sealed result crosses source transactions; provider I/O never runs under SQL. + observation = + prepared.fence() == null + ? null + : consumers.observer().observe(prepared.fence().binding()); + if (!target.equals(readCanonicalScopeTarget(consumers, scope))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } } + // Terminal failures need no remote authority, but retain caller and locked identity checks. recheckCaller.run(); CanonicalJoinResult committed = commitCanonicalJoin( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java index 19f88e13d9..9c5f6a9b38 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -181,7 +181,7 @@ void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { .hasCauseInstanceOf(IllegalStateException.class) .hasRootCauseMessage("controlled capture rollback"); assertThat(captures).hasValue(1); - assertThat(f.dsl().fetchOne("SELECT to_regclass(?)::text", marker).get(0, String.class)) + assertThat(f.dsl().fetchSingle("SELECT to_regclass(?)::text", marker).get(0, String.class)) .isNull(); } 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 262780703c..0093d0d96b 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 @@ -974,11 +974,54 @@ void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMut when(accountJoinOperationRepository.finishCanonicalFailure( f.requestId, f.scope, f.binding, outcome)) .thenReturn(f.pending); + org.mockito.Mockito.doThrow(new IllegalStateException("Game Session unavailable")) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); var result = f.browserJoin(); assertFalse(result.success()); assertTrue(result.replayed()); assertEquals(outcome, result.outcomeCode()); - verifyNoInteractions(f.sources, f.demos, f.hosting, f.observer, f.terminal); + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, outcome); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(2)) + .isAccountSessionActive(f.account.getId(), f.bootstrap); + } + + @Test + void canonicalFailedRetryStillChecksLockedRequestIdentity() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("FAILED"); + when(f.pending.outcome()).thenReturn("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + when(accountJoinOperationRepository.finishCanonicalFailure( + f.requestId, f.scope, f.binding, "PUBLIC_PRODUCTION_ADMISSION_DENIED")) + .thenThrow( + new AccountJoinOperationRepository.CanonicalJoinOperationConflictException( + "Controlled retained identity conflict")); + assertEquals( + "IDEMPOTENCY_CONFLICT", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(2)) + .findCanonicalEvidenceForUpdateByRequestId(f.requestId); + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); + } + + @Test + void canonicalFailedRetryStillRechecksCallerBeforeLockedReplay() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("FAILED"); + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(true, false); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); } @ParameterizedTest From ad43012d911844dc814accc682ee2ab0a19892e4 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 21:07:50 +1300 Subject: [PATCH 31/66] fix(test): re-evaluate replay admission and pin paid failure proofs --- ...nicalFirstJoinPostgresIntegrationTest.java | 20 ++++++++++---- ...untRuntimeStubServerCompatibilityTest.java | 10 +++++++ .../test/AccountRuntimeStubServer.java | 26 ++++++++++++------- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java index 50b3c7a81d..aedb15b4be 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; @@ -113,7 +115,10 @@ void providerFactsChangedBeforeCommitRollbackAllStagedWritesThenSameOriginalCanR var original = c.operation(); c.hosting.providerStatus("canceled"); var contradictory = c.hosting.observer().observe(c.fence.binding()); - assertThatThrownBy(() -> c.commit(contradictory)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> c.commit(contradictory)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: provider facts differ from the committed receipt"); + verifyNoInteractions(c.demos); c.assertRolledBack(original); c.hosting.providerStatus("active"); var recovered = c.hosting.observer().observe(c.fence.binding()); @@ -138,7 +143,10 @@ void expiredPaidReceiptIsUnavailableAndNeverSelectsDemo() { var original = c.operation(); c.hosting.clock().advance(Duration.ofHours(2)); var freshSdkResult = c.hosting.observer().observe(c.fence.binding()); - assertThatThrownBy(() -> c.commit(freshSdkResult)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> c.commit(freshSdkResult)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current receipt is expired or inconsistent"); + verifyNoInteractions(c.demos); c.assertRolledBack(original); } @@ -191,6 +199,7 @@ private static final class Context { private final CanonicalHostingSubscriptionTestFixture.Fixture hosting; private final AccountJoinOperationRepository operations; private final AccountAuthorityOutboxRepository outbox; + private final AccountDemoTenantEntitlementRepository demos; private final AccountMembershipPairAuthorityRepository pairs; private final AccountCanonicalFirstJoinTerminalCoordinator coordinator; private final CanonicalJoinScopeV2 scope; @@ -231,9 +240,10 @@ private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean var billing = new AccountTenantEntitlementOutboxRepository(dsl); var tenantEvents = new AccountTenantAuthorityEventRepository(dsl, outbox, billing, fresh, generations); - var demos = - new AccountDemoTenantEntitlementRepository( - dsl, fresh, generations, billing, tenantEvents); + demos = + spy( + new AccountDemoTenantEntitlementRepository( + dsl, fresh, generations, billing, tenantEvents)); var scopes = new AccountConnectScopeRepository( dsl, diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index bdda13d502..359dea0f2b 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -552,6 +552,16 @@ void joinRetainsTerminalOutcomesAndNewRequestObservesActiveMembership(String lif assertThat(alreadyActive.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) .isEqualTo(after); + + server.denyGameplayAdmission(); + var nonAdmittingReplay = + joined.toBuilder().setReplayed(true).setGameplayAdmissionAllowed(false).build(); + assertThat(stub.joinPublicProductionMembership(nextRequest)).isEqualTo(nonAdmittingReplay); + server.allowGameplayAdmission(); + server.setMembershipInactive(); + assertThat(stub.joinPublicProductionMembership(nextRequest)).isEqualTo(nonAdmittingReplay); + assertThat(stub.joinPublicProductionMembership(request)) + .isEqualTo(denied.toBuilder().setReplayed(true).build()); } finally { channel.shutdownNow(); } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 2cf619a1f4..4a80b18323 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -376,15 +376,23 @@ public synchronized void joinPublicProductionMembership( } else { StubJoinOutcome retained = joinOutcomesByRequestId.get(request.getRequestId()); if (retained != null) { - responseObserver.onNext( - retained.request().equals(request) - ? retained.response().toBuilder().setReplayed(true).build() - : JoinPublicProductionMembershipResponse.newBuilder() - .setError( - ErrorDetail.newBuilder() - .setCode("IDEMPOTENCY_CONFLICT") - .setMessage("Direct-text JOIN request ID conflicts")) - .build()); + if (retained.request().equals(request)) { + var replay = retained.response().toBuilder().setReplayed(true); + if (retained.response().getSuccess()) { + // A retained membership receipt never preserves historical admission permission. + replay.setGameplayAdmissionAllowed( + "ACTIVE".equals(membershipLifecycleState.get()) && gameplayAdmissionAllowed.get()); + } + responseObserver.onNext(replay.build()); + } else { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("IDEMPOTENCY_CONFLICT") + .setMessage("Direct-text JOIN request ID conflicts")) + .build()); + } } else { JoinPublicProductionMembershipResponse response = evaluateJoin(caller); joinOutcomesByRequestId.put(request.getRequestId(), new StubJoinOutcome(request, response)); From 907f9307c325881a976e1bf23b5ce9cf4a8319cb Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 21:22:02 +1300 Subject: [PATCH 32/66] fix(account): clarify retryable target failures and current boundaries --- .../microservices/account-service/api-contracts.md | 2 +- .../implementation-tracking/player-access-and-session.md | 6 +++--- .../accountservice/service/impl/AccountServiceImpl.java | 4 +++- .../accountservice/service/impl/AccountServiceImplTest.java | 4 +++- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 28d1c68b46..b122534fb7 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -155,7 +155,7 @@ The account lifecycle API, export surfaces, and deletion-precondition contracts ### Account Tenant Identifier Boundary -Public bootstrap realm projections (`BootstrapRealmDto`), direct-text caller/target scopes (`DirectTextCallerContext` and `DirectTextJoinTarget`), and explicit public-production JOIN results (`JoinPublicProductionResult` and `JoinPublicProductionMembershipResponse.tenant_id`) carry the canonical non-nil tenant UUID. Bootstrap realm and direct-text target game-instance identifiers likewise carry canonical non-nil UUIDs. The legacy runtime membership, entitlement and realm-grant reads still use the numeric tenant ID, including `GetTenantMembershipForRuntimeResponse.tenant_id`; the legacy Account tenant-export selector also remains numeric. These representations are specific to their contracts and must not be interchanged or inferred from Account UUID identity. Canonical facade inputs do not establish default runtime wiring or gameplay admission. +Public bootstrap realm projections (`BootstrapRealmDto`), direct-text caller/target scopes (`DirectTextCallerContext` and `DirectTextJoinTarget`), and explicit public-production JOIN results (`JoinPublicProductionResult` and `JoinPublicProductionMembershipResponse.tenant_id`) carry the canonical non-nil tenant UUID. Bootstrap realm and direct-text target game-instance identifiers likewise carry canonical non-nil UUIDs. The legacy runtime membership, entitlement and realm-grant reads still use the numeric tenant ID, including `GetTenantMembershipForRuntimeResponse.tenant_id`; the legacy Account tenant-export and profile tenant selectors, including the profile DTO tenant identifier, also remain numeric. These representations are specific to their contracts and must not be interchanged or inferred from Account UUID identity. Canonical facade inputs do not establish default runtime wiring or gameplay admission. ### Account UUID Response and REST Selector Identity 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 f17e8c1db1..837858defe 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -579,7 +579,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.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` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `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) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [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); [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); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [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); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `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); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. 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 shared subscription-version/billing-sequence projection 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. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [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); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.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 [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | @@ -804,7 +804,7 @@ The current numeric-reader guardrail is: numeric identifiers still used by an im This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and current presence projects only `PLAYER` until an independent gameplay-grant carrier exists. JWT global/scoped role claims and cached elevation supply no gameplay authority; broader admission, grant-issuance, and capability qualification remains tracked in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence). Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. -Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, any replay read, token mint, or replay/session mutation. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and preserved obligations. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. +Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing any replay read, token mint, or replay/session mutation. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and preserved obligations. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) uses typed result unions for successfully produced expected domain outcomes and canonical non-OK status with bounded details when a domain result cannot be produced. Current Game Session/peer handlers still return many response-level `ErrorDetail` payloads, while transport failures cover infrastructure and some pre-domain cases; exact per-RPC migration and proof remain gaps. Shared REST exception handling continues to produce `ApiResponse` envelopes and field-specific `INVALID_ARGUMENT` responses instead of framework-default JSON. These seams log application warnings, meter `grpc.app_error` where applicable, and preserve span/error-code classification. @@ -905,7 +905,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and prepared explicit public-production JOIN (default receiving composition returns `AUTH_UNAVAILABLE`); canonical gameplay connect-token receiving currently fails closed before bootstrap/scope validation; current status and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) | Account REST/gRPC APIs, including prepared `/auth/bootstrap/join` and local JOIN RPC contracts (default receiving composition returns `AUTH_UNAVAILABLE`); `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and prepared explicit public-production JOIN (default receiving composition returns `AUTH_UNAVAILABLE`); canonical gameplay connect-token receiving fails closed before bootstrap/scope validation when consumers are absent, or after those checks when manually configured; current status and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) | Account REST/gRPC APIs, including prepared `/auth/bootstrap/join` and local JOIN RPC contracts (default receiving composition returns `AUTH_UNAVAILABLE`); `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, control-plane privilege claims, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and shared pod readiness currently fail closed pending canonical producer/replay/key qualification. The combined readiness hold withdraws both Gateway Service endpoint families; independent route-level Service readiness remains a pre-rollout gap. | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and deployment qualification in [Gateway readiness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness) | 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 56baf5a251..e110dee271 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 @@ -572,7 +572,9 @@ private PublishedRealmEvidence readCanonicalScopePublishedTarget( throw failure; } catch (RuntimeException failure) { throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", STALE_CONNECT_SCOPE_MESSAGE, failure); + "ADMISSION_POINTER_UNAVAILABLE", + "Gameplay target authority is unavailable; retry the same request", + failure); } } 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 0093d0d96b..8fd19f3c28 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 @@ -1272,6 +1272,8 @@ void canonicalJoinRemoteValidationFailureRemainsRetryable(String owner) { } var result = assertThrows(AuthenticationException.class, f::browserJoin); assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.getCode()); + assertEquals( + "Gameplay target authority is unavailable; retry the same request", result.getMessage()); assertSame(failure, result.getCause()); org.mockito.Mockito.verify(accountJoinOperationRepository) .recordCanonicalAttemptFailure( @@ -3026,7 +3028,7 @@ void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { } @Test - void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { + void listBootstrapWorldsMapsUnexpectedJwtParserFailureToUnavailableWithCause() { JwtUtil jwtUtil = org.mockito.Mockito.mock(JwtUtil.class); IllegalStateException parserFailure = new IllegalStateException("boom"); when(jwtUtil.parseToken("boom-token")).thenThrow(parserFailure); From 76e73c02bc49e0bc9e4f2efeb5bd4d292aa775cd Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 22:13:15 +1300 Subject: [PATCH 33/66] fix(account): settle unclaimed wallet-invalidated provisioning --- .../account-service/api-contracts.md | 2 +- .../account-service/runtime-and-data.md | 2 +- ...ostingSubscriptionLifecycleRepository.java | 59 +++++++--- ...9__hosting_unclaimed_wallet_settlement.sql | 10 ++ ...rUuidEntityCompositionIntegrationTest.java | 4 +- ...criptionIntentPostgresIntegrationTest.java | 111 ++++++++++++++++-- ...ourceSelectionPostgresIntegrationTest.java | 1 - 7 files changed, 160 insertions(+), 29 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b122534fb7..085c247868 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -476,7 +476,7 @@ This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Bro The request carries schema version 1, `targetNamespace` matching Account's configured workload namespace, canonical non-nil `tenantId` and `requestId` UUIDs, and an explicit `sourceKind` of exactly `PAID_HOSTING` or `NON_PAID_DEMO`. There is no default, inference or fallback between sources. The paid branch requires a fresh current Account hosting receipt for the exact tenant and matching current tenant-authority evidence; the DEMO branch reads Account's canonical current DEMO entitlement. Account captures complete entitlement facts, tenant-authority/billing-cutoff evidence and outbox checkpoints in the selected owner source transaction. Missing, stale, mismatched or unavailable selected-source authority supplies no success evidence. The response echoes the exact request and carries strict canonical evidence bound to its tenant, request, source kind and authenticated World workload. Repeated transport members each require exactly one value, and unknown fields fail closed. The [closed codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java) owns the 1 KiB request bound, response wire allowance of 64 KiB + 1 KiB + 32 bytes, five-second deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java) owns the 64 KiB canonical content bound. -This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [local source-foundation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). +This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [billing and retention tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). ## Subject-Binding Rules (Normative) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 123f63a387..5c4a3267e0 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -316,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is being qualified in the canonical public receiving branch. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. +The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 2da4599bcc..c8642ee88c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -1219,8 +1219,8 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId try { current = intents.lockForProvisioningRecovery(requestId, versionToLock); } catch (FenceRejectedException refused) { - // A later wallet observation may prevent any further dispatch. Only already retained work - // can use the local settlement fence, and this path never returns a provider-capable claim. + // A later wallet observation may prevent even the first dispatch. The original intent + // can use the local settlement fence, but this path never returns a provider-capable claim. return recoverUndispatchableWork(requestId, versionToLock, prior); } var original = intents.findCreation(requestId).orElseThrow(); @@ -1228,18 +1228,7 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId if (now.isBefore(original.createdAt())) { throw new FenceRejectedException("Provisioning clock predates the durable intent"); } - dsl.execute( - "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " - + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " - + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", - requestId, - original.subscriptionId(), - limits.maximumAttempts(), - limits.maximumStalledAttempts(), - limits.lease().toMillis(), - limits.backoff().toMillis(), - utc(original.createdAt().plus(limits.absoluteTimeout())), - utc(original.createdAt())); + retainUnclaimedWork(original); Record work = workForUpdate(requestId); if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { return new ClaimResult(Disposition.TERMINAL_FAILURE, null); @@ -1324,9 +1313,50 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId return new ClaimResult(Disposition.CLAIMED, claim(original, Objects.requireNonNull(attempt))); } + private void retainUnclaimedWork(AccountSubscriptionCreationRecord original) { + dsl.execute( + "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " + + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + original.requestId(), + original.subscriptionId(), + limits.maximumAttempts(), + limits.maximumStalledAttempts(), + limits.lease().toMillis(), + limits.backoff().toMillis(), + utc(original.createdAt().plus(limits.absoluteTimeout())), + utc(original.createdAt())); + } + private ClaimResult recoverUndispatchableWork(UUID requestId, long version, Record prior) { var current = intents.lockForProvisioningSettlement(requestId, version); + var original = intents.findCreation(requestId).orElseThrow(); + Instant now = now(); + if (now.isBefore(original.createdAt())) { + throw new FenceRejectedException("Provisioning clock predates the durable intent"); + } + retainUnclaimedWork(original); Record work = workForUpdate(requestId); + if (work.get("last_attempt_id") == null) { + if (prior != null + || work.get("attempt_count", Integer.class) != 0 + || !current.subscriptionId().equals(work.get("subscription_id", UUID.class)) + || !"pending".equals(current.status()) + || current.rowVersion() != 1L + || current.providerSubscriptionId() != null + || links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Exact unclaimed provisioning settlement fence rejected"); + } + if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { + return new ClaimResult(Disposition.TERMINAL_FAILURE, null); + } + if (!"RECONCILING".equals(work.get("phase", String.class))) { + throw new FenceRejectedException("Unclaimed provisioning work is not reconciling"); + } + // No claim is issued and no provider absence is inferred. Keep the reservation held and + // retain one operator item even when the wallet changed before work was first claimed. + return fail(work, "RESERVED_INSTRUMENT_CHANGED", now); + } requireUnmappedProvisioningWork(current, work); if (prior != null && !prior.get("attempt_id", UUID.class).equals(work.get("last_attempt_id", UUID.class))) { @@ -1336,7 +1366,6 @@ private ClaimResult recoverUndispatchableWork(UUID requestId, long version, Reco dsl.fetchOne( "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", work.get("last_attempt_id", UUID.class)); - Instant now = now(); if (retained == null || now.isBefore(instant(retained, "claimed_at"))) { throw new FenceRejectedException("Exact retained provisioning attempt is absent or future"); } diff --git a/services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql b/services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql new file mode 100644 index 0000000000..fcd77e4828 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql @@ -0,0 +1,10 @@ +-- A wallet observation can invalidate dispatch before the first worker claim. Retain a terminal +-- operator item without asserting provider absence, canceling the intent, or releasing its hold. +-- [jooq ignore start] +ALTER TABLE subscription_provisioning_operator_outbox + DROP CONSTRAINT subscription_provisioning_operator_outbox_reason_check; +ALTER TABLE subscription_provisioning_operator_outbox + ADD CONSTRAINT subscription_provisioning_operator_outbox_reason_check + CHECK (reason IN ('ABSOLUTE_DEADLINE', 'ATTEMPT_BUDGET', + 'STALLED_WITHOUT_COMMITTED_PROGRESS', 'RESERVED_INSTRUMENT_CHANGED')); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index cd5ee4bd09..bb637f8087 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -262,7 +262,9 @@ void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtls client.init(); facade.setAccountBootstrapRosterReadClient(client); var beforeEmpty = entityRows(entity); - assertThat(listBootstrapCharacters(tokenA, scopeA).isEmpty()).isTrue(); + var emptyRoster = listBootstrapCharacters(tokenA, scopeA); + assertThat(emptyRoster.isArray()).isTrue(); + assertThat(emptyRoster.size()).isZero(); assertThat(entityRows(entity)).isEqualTo(beforeEmpty); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java index 1826f51dd2..8ac4a906e7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java @@ -196,8 +196,12 @@ void provisioningExhaustionCommitsOneOperatorItemWithoutCancellationOrWalletRewr rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription_provisioning_attempts")); } - @Test - void claimRollbackAndStaleReservedWalletCannotLeaveProvisioningWork() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + value = AccountPaymentInstrumentRecord.State.class, + names = {"ATTACHABLE", "UNAVAILABLE"}) + void claimRollbackAndStaleReservedWalletRetainOneTerminalOperatorItem( + AccountPaymentInstrumentRecord.State observedState) { Context c = context(); configuration(c).target("1030").load().migrate(); Seed seed = seed(c); @@ -211,20 +215,107 @@ void claimRollbackAndStaleReservedWalletCannotLeaveProvisioningWork() { }); assertThat(count(c, "subscription_provisioning_work")).isZero(); assertThat(count(c, "subscription_provisioning_attempts")).isZero(); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("pending"); - c.tx() - .executeWithoutResult( - s -> advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID())); + var pending = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + assertThat(pending.status()).isEqualTo("pending"); + var observed = + c.tx() + .execute( + s -> + new AccountPaymentInstrumentRepository(c.dsl()) + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + seed.instrument().instrumentUuid(), + seed.owner().accountUuid(), + 1L, + observedState, + seed.instrument().display(), + DIGEST))); + // Upgrade the original pending intent and its changed wallet without recreating either row. + configuration(c).load().migrate(); assertThatThrownBy( () -> c.tx() .execute( - s -> lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()))) + s -> lifecycle(c, start).claim(created.requestId(), 2, UUID.randomUUID()))) .isInstanceOf(FenceRejectedException.class); + assertThatThrownBy( + () -> + c.tx() + .execute( + s -> + lifecycle(c, created.createdAt().minusSeconds(1)) + .claim(created.requestId(), 1, UUID.randomUUID()))) + .isInstanceOf(FenceRejectedException.class); + c.tx() + .executeWithoutResult( + s -> { + assertThat( + lifecycle(c, start) + .claim(created.requestId(), 1, UUID.randomUUID()) + .disposition()) + .isEqualTo( + AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + s.setRollbackOnly(); + }); assertThat(count(c, "subscription_provisioning_work")).isZero(); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().rowVersion()) - .isOne(); + assertThat(count(c, "subscription_provisioning_operator_outbox")).isZero(); + UUID firstAttempt = UUID.randomUUID(); + for (UUID attempt : List.of(firstAttempt, firstAttempt, UUID.randomUUID())) { + var result = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c, start).claim(created.requestId(), 1, attempt))); + assertThat(result.disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + assertThat(result.claim()).isNull(); + } + assertThat( + Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, start.plusSeconds(7200)) + .claim(created.requestId(), 1, UUID.randomUUID()))) + .disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + assertThat(count(c, "subscription_provisioning_work")).isOne(); + assertThat(count(c, "subscription_provisioning_attempts")).isZero(); + assertThat(count(c, "subscription_provider_dispatch_claim")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); + var work = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_provisioning_work WHERE request_id = ?", + created.requestId())); + assertThat(work.get("phase", String.class)) + .isEqualTo("BILLING_RECONCILIATION_TERMINAL_FAILURE"); + assertThat(work.get("attempt_count", Integer.class)).isZero(); + assertThat(work.get("row_version", Long.class)).isEqualTo(2L); + assertThat(work.get("last_attempt_id")).isNull(); + var notice = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_provisioning_operator_outbox WHERE request_id = ?", + created.requestId())); + assertThat(notice.get("reason", String.class)).isEqualTo("RESERVED_INSTRUMENT_CHANGED"); + assertThat(notice.get("recorded_at")).isEqualTo(work.get("terminal_at")); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow()).isEqualTo(pending); + assertThat( + new AccountPaymentInstrumentRepository(c.dsl()) + .findByOwner(seed.owner().accountUuid(), seed.instrument().instrumentUuid()) + .orElseThrow()) + .isEqualTo(observed); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + created.requestId())) + .get("released_at")) + .isNull(); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java index 62f15145c9..965acade65 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java @@ -267,7 +267,6 @@ private static Context context() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration", "classpath:db/migration/saga") - .target("1030") .load() .migrate(); var f = CanonicalHostingSubscriptionTestFixture.create(source); From 21726d313f7ee746a709602b4f5cbedf93122448 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 22:47:23 +1300 Subject: [PATCH 34/66] Validate restored JOIN role bindings and precise refusal proofs --- .../account-service/runtime-and-data.md | 2 +- dev-tools/smoke/smoke_common.py | 16 ++-- dev-tools/tests/smoke-transport-contract.sh | 48 ++++++++++++ ...countMembershipAuthorityEventProducer.java | 15 ++-- ...thorityEventProducerCanonicalJoinTest.java | 78 +++++++++++++++++++ .../service/impl/AccountServiceImplTest.java | 46 +++++++++-- 6 files changed, 181 insertions(+), 24 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5c4a3267e0..861dbf789c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -355,7 +355,7 @@ Existing `AccountRealmAccessGrant` persistence and registered internal grant rea - Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- 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. With the default composition absent, current public bootstrap discovery, direct-scope, JOIN, and connect-token receivers return `AUTH_UNAVAILABLE` before applicable validation or authority reads. When manually configured, direct-scope and JOIN proceed into their owner/consumer validation, and connect-token validates bootstrap identity and reads scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. With the default composition absent, the Account JOIN receiving method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; gRPC peer/shape checks can refuse before the service call; the public Gateway route remains blocked by its explicit guard. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) for the held boundary and preserved component obligations/proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- 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. With the default composition absent, current public bootstrap discovery, direct-scope, JOIN, and connect-token receivers return `AUTH_UNAVAILABLE` before applicable validation or authority reads. When manually configured, direct-scope and JOIN proceed into their owner/consumer validation, and connect-token validates bootstrap identity and reads scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. gRPC peer/shape checks can refuse before the JOIN service call, and the public Gateway route remains blocked by its explicit guard. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. The prepared JOIN component re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. With the default composition absent, the JOIN receiver returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. This does not establish default runtime exposure or qualified live JOIN. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 4820eef768..31384254e6 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -313,14 +313,6 @@ def run_transport_session( if time.time() >= deadline: raise continue - except retriable_exceptions as exc: - try: - session.close() - except Exception as close_exc: # noqa: BLE001 - transport close failures vary by client - raise ProbeOperationalFailure( - f"Failed during {session_label}: {exc}; close failed: {close_exc}" - ) from exc - raise ProbeOperationalFailure(f"Failed during {session_label}: {exc}") from exc except PlayEntitlementUnavailable: # The temporary CI classification also requires a clean transport close. try: @@ -330,6 +322,14 @@ def run_transport_session( f"Failed to close {session_label} after known PLAY refusal: {close_exc}" ) from close_exc raise + except retriable_exceptions as exc: + try: + session.close() + except Exception as close_exc: # noqa: BLE001 - transport close failures vary by client + raise ProbeOperationalFailure( + f"Failed during {session_label}: {exc}; close failed: {close_exc}" + ) from exc + raise ProbeOperationalFailure(f"Failed during {session_label}: {exc}") from exc except Exception: # A secondary close failure must not hide the primary command failure. with contextlib.suppress(Exception): diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 2e8e04a307..e6e5a30bed 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -1881,6 +1881,54 @@ assert len(close_failure_attempts) == 1 assert close_failure_attempts[0].closed is True +def test_known_play_exception_precedes_retriable_exceptions(): + for retriable in (OSError, smoke_common.ProbeOperationalFailure, RuntimeError): + for close_fails in (False, True): + opened = [] + failure = smoke_common.PlayEntitlementUnavailable("ERROR ENTITLEMENT_UNAVAILABLE") + + class KnownPlaySession: + closed = False + + def close(self): + self.closed = True + if close_fails: + raise OSError("close failed") + + def open_session(): + session = KnownPlaySession() + opened.append(session) + return session + + def execute_session(_session): + raise failure + + try: + run_transport_session( + open_session, + execute_session, + "known PLAY session", + retry_window_seconds=1, + retry_interval_seconds=0, + retriable_exceptions=(retriable,), + ) + except smoke_common.ProbeOperationalFailure as exc: + if close_fails: + assert type(exc) is smoke_common.ProbeOperationalFailure + assert "Failed to close known PLAY session after known PLAY refusal" in str(exc) + assert isinstance(exc.__cause__, OSError) + assert str(exc.__cause__) == "close failed" + else: + assert exc is failure + else: + raise AssertionError("Known PLAY refusal was concealed") + assert len(opened) == 1 + assert opened[0].closed is True + + +test_known_play_exception_precedes_retriable_exceptions() + + known_play_failure = smoke_common.PlayEntitlementUnavailable("ERROR ENTITLEMENT_UNAVAILABLE") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 8cb87334b2..3bd0c64daa 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -211,10 +211,8 @@ public Checkpoint publishCanonicalRestoredMembershipChange( membership.getId(), membership.getMembershipVersion()) .orElseThrow(); - if (roles.snapshotVersion() != membership.getMembershipVersion() - || !roles.roles().contains("player")) { - throw new IllegalStateException("Restore event requires exact current player roles"); - } + List exactRoles = + requireCanonicalJoinRoleSnapshot(scope, membership, provenance, roles); CompositeSnapshot authority = authorityGenerationRepository.readCompositeSnapshot( ACCOUNT_JWT_ISSUER, @@ -286,7 +284,7 @@ public Checkpoint publishCanonicalRestoredMembershipChange( membershipEventPreimage( scope, membership, - roles.roles(), + exactRoles, authority, sources, tenant, @@ -404,7 +402,8 @@ private Checkpoint publishCanonicalFirstJoinMembershipChange( membership.getMembershipVersion()) .orElseThrow( () -> new IllegalStateException("Canonical first-JOIN role snapshot is absent")); - List exactRoles = requireFirstJoinRoleSnapshot(scope, membership, provenance, roles); + List exactRoles = + requireCanonicalJoinRoleSnapshot(scope, membership, provenance, roles); PairAuthority pair = pairAuthorityRepository @@ -874,7 +873,7 @@ private record PaidJoinSource( } } - private static List requireFirstJoinRoleSnapshot( + private static List requireCanonicalJoinRoleSnapshot( CanonicalJoinScopeV2 scope, AccountTenantMembership membership, VerifiedTenantProvenance provenance, @@ -889,7 +888,7 @@ private static List requireFirstJoinRoleSnapshot( if (roles.accountId() != membership.getAccount().getId() || roles.tenantId() != null || roles.membershipId() != membership.getId() - || roles.snapshotVersion() != 2L + || roles.snapshotVersion() != membership.getMembershipVersion() || !scope.accountId().equals(roles.accountUuid()) || !scope.tenantId().equals(roles.tenantUuid()) || !provenance.equals(roles.tenantProvenance()) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 237442cc7a..181ad55ea3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -159,6 +159,84 @@ void restoreRejectsContradictoryAccountIdentityBeforeLocking(String malformed) { fixture.entitlements); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = { + "account-id", "membership-id", "legacy-tenant", "account-uuid", "tenant-uuid", + "provenance", "version", "unsorted", "duplicate", "missing-player" + }) + void restoreRejectsUnboundOrNoncanonicalRoleSnapshotBeforeAuthorityReads(String malformed) { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + fixture.membership.setMembershipVersion(4L); + fixture.membership.setMembershipAuthorityGeneration(2L); + var previous = + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + fixture.provenance, + true, + 3L, + 2L, + 2L, + UUID.randomUUID().toString(), + DIGEST, + true); + when(fixture.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(fixture.account)); + when(fixture.joinOperations.findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(fixture.operation(CALLER_BINDING))); + when(fixture.pairs.readForUpdate(ACCOUNT_UUID, TENANT_UUID)).thenReturn(Optional.of(previous)); + when(fixture.memberships.findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(Optional.of(fixture.membership)); + // Deliberately bypass the record's own construction checks to exercise the producer boundary. + var roles = + mock( + RoleSnapshot.class, + org.mockito.AdditionalAnswers.delegatesTo( + new RoleSnapshot( + 17L, + null, + 73L, + 4L, + List.of("player"), + ACCOUNT_UUID, + TENANT_UUID, + fixture.provenance))); + switch (malformed) { + case "account-id" -> when(roles.accountId()).thenReturn(18L); + case "membership-id" -> when(roles.membershipId()).thenReturn(74L); + case "legacy-tenant" -> when(roles.tenantId()).thenReturn(9L); + case "account-uuid" -> when(roles.accountUuid()).thenReturn(UUID.randomUUID()); + case "tenant-uuid" -> when(roles.tenantUuid()).thenReturn(UUID.randomUUID()); + case "provenance" -> when(roles.tenantProvenance()).thenReturn(null); + case "version" -> when(roles.snapshotVersion()).thenReturn(3L); + case "unsorted" -> when(roles.roles()).thenReturn(List.of("player", "admin")); + case "duplicate" -> when(roles.roles()).thenReturn(List.of("player", "player")); + case "missing-player" -> when(roles.roles()).thenReturn(List.of("admin")); + default -> throw new AssertionError(malformed); + } + when(fixture.roles.findForCanonicalUpdate( + ACCOUNT_UUID, TENANT_UUID, fixture.provenance, 73L, 4L)) + .thenReturn(Optional.of(roles)); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, previous, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + List.of("unsorted", "duplicate").contains(malformed) + ? "Canonical JOIN role snapshot is not canonical" + : "Canonical JOIN role snapshot differs from its exact membership source or lacks player role"); + verifyNoInteractions( + fixture.authority, + fixture.sourceEvidence, + fixture.tenantAuthorityEvents, + fixture.entitlements, + fixture.outbox); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.CsvSource({ "request,null", 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 8fd19f3c28..8413cad97c 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 @@ -1444,7 +1444,11 @@ void canonicalJoinConflictingRequestDoesNotReplaceOriginalEvidence() { void canonicalJoinCurrentAccountLifecycleBlocksAStillLiveBootstrap(AccountLifecycleState state) { var f = canonicalJoinFixture(); f.account.setLifecycleState(state); - assertThrows(AuthenticationException.class, f::browserJoin); + assertEquals( + state == AccountLifecycleState.SECURITY_LOCKED + ? "AUTH_ACCOUNT_LOCKED" + : "AUTH_INVALID_CREDENTIALS", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); verifyNoInteractions(f.terminal); } @@ -2092,7 +2096,14 @@ void canonicalBootstrapCharactersRechecksMembershipAfterEntityRead() { new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient .Actor(UUID.randomUUID(), "Ada", 12)); }); - assertThrows(AuthenticationException.class, f::characters); + var failure = assertThrows(AuthenticationException.class, f::characters); + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + assertEquals("Bootstrap membership changed during discovery", failure.getMessage()); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @@ -2331,16 +2342,37 @@ void canonicalBootstrapCharactersExplicitlyRefusesUnsupportedIsolatedScope() { } /** - * Denial proof only: PLAYER_CREATED/AUTO/private/ISOLATED positive branches remain unfinished. + * Controlled late-owner refusal only; retained resolution still rejects unsupported policies. + * PLAYER_CREATED/AUTO/private/ISOLATED positive branches remain unfinished. */ @ParameterizedTest @ValueSource(strings = {"PLAYER_CREATED", "AUTO_PROVISIONED"}) - void canonicalBootstrapCharactersDoesNotPretendUnsupportedPolicyIsAnEmptyRoster(String policy) { + void canonicalBootstrapCharactersRejectsUnsupportedPolicyFromLateControlledOwnerRead( + String policy) { var f = canonicalJoinFixture(); f.joined.set(true); - when(f.target.characterCreationPolicy()).thenReturn(policy); - assertThrows(AuthenticationException.class, f::characters); - verifyNoInteractions(f.roster); + // Retained resolution admits PRESEEDED_ONLY only. Change this controlled owner response + // after that check to exercise the facade's own unsupported-policy refusal, not the codec. + when(f.targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + when(f.target.characterCreationPolicy()).thenReturn(policy); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(invocation.getArgument(0)); + when(published.currentTarget()).thenReturn(f.target); + return published; + }); + var failure = assertThrows(AuthenticationException.class, f::characters); + assertEquals("REALM_UNAVAILABLE", failure.getCode()); + assertEquals( + "Bootstrap actor discovery does not yet support this realm policy", failure.getMessage()); + org.mockito.Mockito.verify(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(f.sources, f.demos, f.roster); } @Test From bb12a636caa784c8ed87d9bef0402cbdb66752e0 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 23:11:51 +1300 Subject: [PATCH 35/66] Close partial composition resources and clarify contract ownership --- .../account-service/runtime-and-data.md | 18 ++--- .../architecture/system-architecture-cicd.md | 4 +- ...rUuidEntityCompositionIntegrationTest.java | 67 ++++++++++++++++++- ...horityProducerPostgresIntegrationTest.java | 2 +- 4 files changed, 75 insertions(+), 16 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 861dbf789c..40a9cc18ea 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -66,11 +66,11 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; the gRPC adapter can refuse peer or request-shape failures before the service call. The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Current JOIN receiver composition and refusal boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis). The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` 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. With the default composition absent, current public bootstrap discovery, direct-scope, JOIN, and connect-token receivers return `AUTH_UNAVAILABLE` before applicable validation or authority reads. When manually configured, direct-scope and JOIN proceed into their owner/consumer validation, and connect-token validates bootstrap identity and reads scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the default receiving facade returns `AUTH_UNAVAILABLE` before reaching it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `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 numeric runtime entitlement endpoint returns retryable `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` 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 `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` 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 receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `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 numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` 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` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -78,7 +78,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live. Password-reset completion now uses an owner-locked atomic token claim/consume, Account update, canonical event and operation receipt, and current-source readback; an unresolved prior source intent fences token/password mutation and returns retryable `AUTH_UNAVAILABLE` until an exact retry can establish its outcome. `AccountAuthoritySourceEventReadback` accepts only the supported closed-operation event shapes with their exact immutable operation receipts; generic Account authority events without that receipt remain unreadable as current source evidence and fail closed as `AUTH_UNAVAILABLE`. This does not establish complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. Exact retry, concurrent reuse, and physical PostgreSQL proof for this cut remain pending under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -With default composition absent, Account public bootstrap, `IssueDirectTextConnectScope`, `JoinPublicProductionMembership`, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](./api-contracts.md); connect-token remains unavailable after bootstrap/scope validation, before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -201,7 +201,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. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token issuance remains unavailable before membership, entitlement, target-authority, or cached-result processing; the [Account API contract](./api-contracts.md#rest-apis) distinguishes absent consumers from manually configured bootstrap/scope validation. None of these paths creates or restores membership. Account's owner-local public-production JOIN v2 remains a prepared persistence component, but the default receiving facade returns `AUTH_UNAVAILABLE` before reaching it. First-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. 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. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token and JOIN receiver composition is defined by [Account API Contracts](./api-contracts.md#rest-apis). None of these paths creates or restores membership. Account's owner-local public-production JOIN v2 remains a prepared persistence component under that API boundary. First-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. 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. @@ -261,7 +261,7 @@ Runtime caller contract: - Target success delivery uses only `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is not returned in the response body or a response-header fallback. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before creating a token or cookie, so no current first-party WebSocket admission is established. Under the target flow, browser/mobile clients and first-party non-browser clients with a protected cookie jar remain cookie-only. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. -- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. A prepared Account `IssueDirectTextConnectScope` component can receive trusted caller context and the exact Game Session-resolved target, validate the current catalog/pointer snapshot, and return an opaque scope. With the default scope producer absent, the receiving method returns `AUTH_UNAVAILABLE`; when manually configured, it delegates to the scope owner for caller/target validation and scope issuance. This is not default runtime exposure or end-to-end proof. Game Session wiring from text `REALMS`, transport-local scope retention, and subsequent text `JOIN` dispatch (#2898) remain unimplemented; the end-to-end producer flow and proof remain incomplete. +- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. A prepared Account `IssueDirectTextConnectScope` component can receive trusted caller context and the exact Game Session-resolved target, validate the current catalog/pointer snapshot, and return an opaque scope. Current receiver composition and failure behavior are defined by [Account API Contracts](./api-contracts.md#grpc-apis). This is not default runtime exposure or end-to-end proof. Game Session wiring from text `REALMS`, transport-local scope retention, and subsequent text `JOIN` dispatch (#2898) remain unimplemented; the end-to-end producer flow and proof remain incomplete. - `connectScopeExpiresAt` bounds how long the discovery-issued selector may be reused as a convenience token. Once it expires, callers must rerun discovery instead of treating the selector as a durable realm handle. - Account Service must expose bootstrap-discovery endpoints that accept only the `player-bootstrap` token profile and return the canonical caller-visible worlds, realms, characters, and a canonical `connectScopeId` selector for each admissible realm target. - Account Service must use the authoritative realm-routing contract when issuing `/auth/connect-token` so connect-token scope is pinned to the tenant's current admissible instance for the selected realm instead of a caller-supplied guess. @@ -316,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#grpc-apis). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences @@ -353,11 +353,11 @@ Existing `AccountRealmAccessGrant` persistence and registered internal grant rea ### Runtime Implementation Status and Drift -- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. +- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- 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. With the default composition absent, current public bootstrap discovery, direct-scope, JOIN, and connect-token receivers return `AUTH_UNAVAILABLE` before applicable validation or authority reads. When manually configured, direct-scope and JOIN proceed into their owner/consumer validation, and connect-token validates bootstrap identity and reads scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. gRPC peer/shape checks can refuse before the JOIN service call, and the public Gateway route remains blocked by its explicit guard. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- 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 receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The public Gateway route remains blocked by its explicit guard. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. -The prepared JOIN component re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. With the default composition absent, the JOIN receiver returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. This does not establish default runtime exposure or qualified live JOIN. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). +The prepared JOIN component re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries. This does not establish default runtime exposure or qualified live JOIN. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on the JOIN receipt and unknown-outcome reconciliation work in #2848. No universal retention duration is implied. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index c25cd9bb55..887ca6c3e4 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,7 +88,7 @@ A typed runtime refresh hands off publication explicitly after its required cred The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose source `pull_request` event and current live PR both carry the `canonical-play-transition` label, only for the exact verified PR-event base/head/merge tuple and latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose source `pull_request` event and current live PR both carry the `canonical-play-transition` label, only for the exact verified PR-event base/head/merge tuple and latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. The step-independent producer guarantee is bound to one SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. This single fingerprint is part of the owning workflows, not a separate proof registry. @@ -434,5 +434,3 @@ CI workflows and operators use distinct credentials for each Kubernetes environm - No workflow currently proves this target; production apply remains manual implementation debt. A generic GitHub Environment approval of a mutable branch or free-form inputs is insufficient. Registry credentials (for GHCR) are shared across environments but access to pull images into each cluster is controlled by Kubernetes secrets and RBAC within that environment. - -The required Smoke Gate normally needs qualified runtime smoke under the contract above. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index bb637f8087..8334d3b361 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -25,6 +25,9 @@ import java.security.cert.CertificateEncodingException; import java.time.Clock; import java.time.Instant; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -221,6 +224,35 @@ static void stopEntityRuntime() throws Exception { if (entityPostgres.isRunning()) entityPostgres.stop(); } + @org.junit.jupiter.api.Test + void failedEntityStartupClosesEveryRegisteredResourceDespiteCleanupFailures() { + var failure = new IOException("Entity startup failed"); + var clientFailure = new IOException("Owner client cleanup failed"); + var sourceFailure = new IllegalStateException("Source server cleanup failed"); + var closed = new ArrayList(); + Deque resources = new ArrayDeque<>(); + resources.push(() -> closed.add("postgres")); + resources.push( + () -> { + closed.add("source server"); + throw sourceFailure; + }); + resources.push( + () -> { + closed.add("owner client"); + throw clientFailure; + }); + resources.push(() -> closed.add("meters")); + resources.push(() -> closed.add("entity server")); + + closeFailedStartup(failure, resources); + + assertThat(closed) + .containsExactly("entity server", "meters", "owner client", "source server", "postgres"); + assertThat(failure.getSuppressed()).containsExactly(clientFailure, sourceFailure); + assertThat(resources).isEmpty(); + } + @org.junit.jupiter.api.Test @org.springframework.test.annotation.DirtiesContext void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtlsReads() @@ -814,6 +846,11 @@ private static AccountBootstrapRosterReadClient newRosterClient() { private static synchronized EntityRuntime requireEntityRuntime() { if (entityRuntime != null) return entityRuntime; + Deque startedResources = new ArrayDeque<>(); + startedResources.push( + () -> { + if (entityPostgres.isRunning()) entityPostgres.stop(); + }); try { if (!entityPostgres.isRunning()) entityPostgres.start(); var ds = @@ -839,6 +876,7 @@ private static synchronized EntityRuntime requireEntityRuntime() { var repository = new CharacterRepository(dsl); var reads = new AtomicInteger(); Server sourceServer = startSourceServer(reads); + startedResources.push(() -> stopFixtureServer(sourceServer)); var endpoints = new ServiceEndpointsProperties(); endpoints.setGameSessionService("localhost:" + sourceServer.getPort()); var client = @@ -847,6 +885,7 @@ private static synchronized EntityRuntime requireEntityRuntime() { TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("entity-client")), new GrpcChannelFactory(), TEST_NAMESPACE); + startedResources.push(client); client.init(); var service = new AccountBootstrapRosterReadService( @@ -854,6 +893,7 @@ private static synchronized EntityRuntime requireEntityRuntime() { repository, manager); var meters = new SimpleMeterRegistry(); + startedResources.push(meters::close); var identity = TEST_PKI.identity("entity"); Server server = NettyServerBuilder.forPort(0) @@ -871,19 +911,40 @@ private static synchronized EntityRuntime requireEntityRuntime() { .addService( ServerInterceptors.intercept( ordinaryReceiver(repository, meters), new GrpcPeerIdentityInterceptor())) - .build() - .start(); + .build(); + startedResources.push(() -> stopFixtureServer(server)); + server.start(); entityRuntime = new EntityRuntime( repository, jdbc, dsl, manager, server, sourceServer, client, reads, meters); return entityRuntime; } catch (IOException | CertificateEncodingException | RuntimeException failure) { - if (entityPostgres.isRunning()) entityPostgres.stop(); + closeFailedStartup(failure, startedResources); throw new IllegalStateException( "Could not start the real Entity mTLS owner fixture", failure); } } + private static void closeFailedStartup(Throwable failure, Deque resources) { + boolean interrupted = false; + while (!resources.isEmpty()) { + try { + resources.pop().close(); + } catch (Exception cleanup) { + failure.addSuppressed(cleanup); + if (cleanup instanceof InterruptedException) interrupted = true; + } + } + if (interrupted) Thread.currentThread().interrupt(); + } + + private static void stopFixtureServer(Server server) throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Entity fixture gRPC server did not terminate"); + } + } + private static Server startSourceServer(AtomicInteger reads) throws IOException { var identity = TEST_PKI.identity("gs"); return NettyServerBuilder.forPort(0) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index 5bd793cce0..f5952eeb40 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -786,7 +786,7 @@ private AccountServiceImpl newService( fixture.logoutAllOperations(), fixture.securityStateOperations(), fixture.sourceChanges(), - null, // connect scopes + null, // audit outbox is not on the password-reset path null, // join operations null, // email login challenges null, // realm grants From f690d88089be8570dd3f1a01925a0140724310e7 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 23:38:03 +1300 Subject: [PATCH 36/66] Bound transient Gradle distribution download retries --- gradle/wrapper/gradle-wrapper.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5907d39c37..07647661e1 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -2,8 +2,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607 distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip -networkTimeout=10000 -retries=0 +networkTimeout=60000 +retries=3 retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME From 3e12ffc2905fabd390476da77d2447582a5d7542 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 23:49:04 +1300 Subject: [PATCH 37/66] Classify null JOIN outcomes and share canonical owner validation --- .../player-access-and-session.md | 4 +- .../AccountJoinOperationRepository.java | 9 ++- ...countMembershipAuthorityEventProducer.java | 59 +++++++++---------- ...tJoinOperationRepositoryCanonicalTest.java | 38 ++++++++++++ 4 files changed, 73 insertions(+), 37 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 837858defe..15778e7116 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -574,7 +574,7 @@ With canonical scope consumers absent from the default composition, Account conn | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.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); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.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 V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; tenant IDs remain numeric and full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.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); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.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 V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; profile and legacy runtime/export tenant IDs remain numeric, while public bootstrap, direct-text scope and JOIN results follow the [Account tenant identifier boundary](../../architecture/microservices/account-service/api-contracts.md#account-tenant-identifier-boundary); full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [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. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.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` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `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) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [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); [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); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [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); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | @@ -656,7 +656,7 @@ Local receipt of the REST selector source preserves the future UUID ordinary iss #### Ordinary Account UUID receiving preparation -The final ordinary receiving source converges password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Profile `SessionContext` self-binding and global REST caller proof also use UUID identity; Account alone resolves UUIDs to private rows through persisted provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant identifiers retain their current numeric representation. The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. R1251 qualifies the actual Account-issued UUID credential through real intake composition. Final receiving proof and its boundaries are recorded below. +The final ordinary receiving source converges password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Profile `SessionContext` self-binding and global REST caller proof also use UUID identity; Account alone resolves UUIDs to private rows through persisted provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant representations follow the [Account tenant identifier boundary](../../architecture/microservices/account-service/api-contracts.md#account-tenant-identifier-boundary). The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. R1251 qualifies the actual Account-issued UUID credential through real intake composition. Final receiving proof and its boundaries are recorded below. Earlier composition runs remain separately attributed: R1228 passes 2,840 Game Session units, 22 WebSocket cases, 145 Social units, 16 Social native cases and eight Account native cases, but its aggregate fails Account test compilation; R1230 recovers the corrected Account suite with 1,797 passes and four existing conditional skips, plus affected test analysis/formatting. They are predecessor-source history, not the final qualification. Current Social V1003 and Logging V1003 follow their effective shared-saga V1002 parents; R1235 passes seven Social physical PostgreSQL cases, and R1239 passes two Logging physical cases plus generation, parent-aware ordering and affected analysis/formatting. Both migrations lock affected tables, refuse populated legacy references and preserve rows/history without guessed mappings, deletion or backfill. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index 8977650524..60d9ce907c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -468,6 +468,9 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( String outcome, CanonicalJoinTerminalProof proof) { requireWritableOwnerTransaction(); + if (outcome == null || !Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome)) { + throw new CanonicalJoinOperationConflictException("Canonical JOIN outcome/proof conflict"); + } requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); Objects.requireNonNull(proof, "Canonical first-JOIN terminal proof is required"); @@ -493,8 +496,7 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); requireCanonicalPolicyMatch(operation, requestDigest, publicJoin, proof.entitlementVersion()); requireTerminalProofScope(proof, requestId, scope, operation); - if (!Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome) - || ("JOINED".equals(outcome) != (proof.auditEventId() != null))) { + if ("JOINED".equals(outcome) != (proof.auditEventId() != null)) { throw new CanonicalJoinOperationConflictException("Canonical JOIN outcome/proof conflict"); } if ("COMMITTED".equals(operation.status())) { @@ -1041,7 +1043,8 @@ public CanonicalJoinOperationEvidence( || membershipVersion != null || membershipAuthorityGeneration != null || terminalProof != null - : !Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome) + : outcome == null + || !Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome) || membershipId == null || membershipId <= 0L || membershipVersion == null diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 3bd0c64daa..1c29990421 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -157,22 +158,8 @@ public Checkpoint publishCanonicalRestoredMembershipChange( requireBoundedText(requestId, "canonical JOIN request ID", MAX_REQUEST_ID_LENGTH); requireBoundedText(callerBinding, "verified JOIN caller binding", MAX_CALLER_BINDING_LENGTH); Objects.requireNonNull(previous); - if (hosting != null) { - Objects.requireNonNull(fence, "Original paid read fence required"); - Objects.requireNonNull(observed, "Original sealed SDK result required"); - } - var account = - accountRepository - .findByAccountUuid(scope.accountId()) - .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); - if (account.getId() == null - || account.getId() <= 0L - || !scope.accountId().equals(account.getAccountUuid()) - || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) - || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { - throw new IllegalStateException("Canonical Account owner identity is contradictory"); - } - joinOperationRepository.lockAccount(account.getId()); + PaidJoinSource paid = hosting == null ? null : new PaidJoinSource(hosting, fence, observed); + var account = lockCanonicalAccountOwner(scope.accountId()); CanonicalJoinOperationEvidence operation = joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); requireOperationMatchesRequest(scope, requestId, callerBinding, account.getId(), operation); @@ -234,7 +221,7 @@ public Checkpoint publishCanonicalRestoredMembershipChange( membership, provenance, tenant); - if (hosting == null) { + if (paid == null) { requireCurrentJoinEntitlement( operation, demoTenantEntitlementRepository.readCurrent(scope.tenantId()), @@ -242,7 +229,10 @@ public Checkpoint publishCanonicalRestoredMembershipChange( scope.tenantId()); } else { requireCurrentPaidJoinEntitlement( - operation, hosting.readCurrent(fence, observed), tenant, scope.tenantId()); + operation, + paid.hosting().readCurrent(paid.fence(), paid.observed()), + tenant, + scope.tenantId()); } String stream = membershipStreamKey(scope.accountId(), scope.tenantId()); Checkpoint prior = authorityOutboxRepository.readCheckpoint(stream).orElseThrow(); @@ -356,20 +346,7 @@ private Checkpoint publishCanonicalFirstJoinMembershipChange( UUID accountUuid = scope.accountId(); UUID tenantUuid = scope.tenantId(); - var account = - accountRepository - .findByAccountUuid(accountUuid) - .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); - if (account.getId() == null - || account.getId() <= 0L - || !accountUuid.equals(account.getAccountUuid()) - || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) - || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { - throw new IllegalStateException("Canonical Account owner identity is contradictory"); - } - // The operation repository exposes only a retained private row key. Lock its actual Account - // owner first, then lock/read the operation before resolving any membership source evidence. - joinOperationRepository.lockAccount(account.getId()); + var account = lockCanonicalAccountOwner(accountUuid); CanonicalJoinOperationEvidence operation = joinOperationRepository .findCanonicalEvidenceForUpdateByRequestId(requestId) @@ -862,6 +839,24 @@ private static void requireCurrentPaidJoinEntitlement( } } + private Account lockCanonicalAccountOwner(UUID accountUuid) { + var account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); + if (account.getId() == null + || account.getId() <= 0L + || !accountUuid.equals(account.getAccountUuid()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException("Canonical Account owner identity is contradictory"); + } + // The operation repository exposes only a retained private row key. Lock its actual Account + // owner first, then lock/read the operation before resolving any membership source evidence. + joinOperationRepository.lockAccount(account.getId()); + return account; + } + private record PaidJoinSource( AccountHostingSubscriptionLifecycleRepository hosting, ReadFence fence, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java index acfc3ea06e..223917f24c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -2,17 +2,24 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountJoinOperationRepositoryCanonicalTest { private static final String STREAM = @@ -108,6 +115,37 @@ void failedEvidenceMayRetainPolicyButCannotCarrySuccessProofOrRetryableOutcome() } /** Controlled journal content, not caller authentication or entitlement source evidence. */ + @Test + void committedNullOutcomeIsClassifiedAsInconsistentTerminalEvidence() { + assertThatThrownBy( + () -> evidence(true, "COMMITTED", null, "AVAILABLE", null, validProof(), 73L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical JOIN terminal evidence is inconsistent"); + } + + @Test + void nullCommitOutcomeIsClassifiedBeforeOwnerStorageReads() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + var repository = new AccountJoinOperationRepository(dsl, scopes); + boolean active = TransactionSynchronizationManager.isActualTransactionActive(); + boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + assertThatThrownBy( + () -> + repository.commitCanonicalJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", null, validProof())) + .isInstanceOf(CanonicalJoinOperationConflictException.class) + .hasMessage("Canonical JOIN outcome/proof conflict"); + verifyNoInteractions(dsl, scopes); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(active); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + } + } + private static CanonicalJoinOperationEvidence evidence( boolean bound, String status, From 4de1a3e2f5b2ac01e5abbca4c0235d71fca3535b Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 00:26:59 +1300 Subject: [PATCH 38/66] Classify absent direct callers and tighten JOIN terminal guards --- ...CanonicalFirstJoinTerminalCoordinator.java | 35 ++++++--------- ...AccountCanonicalPublicRealmScopeOwner.java | 8 +++- ...ical_join_existing_membership_terminal.sql | 2 +- ...anonicalFirstJoinEventIntegrationTest.java | 44 +++++++++++++++++++ ...nicalFirstJoinTerminalCoordinatorTest.java | 11 +++++ ...untCanonicalPublicRealmScopeOwnerTest.java | 40 +++++++++++++++++ 6 files changed, 116 insertions(+), 24 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index 245397ad3f..283d449115 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -166,15 +166,13 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( .findCanonicalEvidenceForUpdateByRequestId(requestId) .orElseThrow(); } - if ("PENDING".equals(operation.status())) { - eventProducer.requireCurrentCanonicalJoinPolicy( - scope, - operation, - !"ACTIVE".equals(membership.getLifecycleState()), - hosting, - fence, - observed); - } + eventProducer.requireCurrentCanonicalJoinPolicy( + scope, + operation, + !"ACTIVE".equals(membership.getLifecycleState()), + hosting, + fence, + observed); VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); RoleSnapshot roles = roleSnapshotRepository @@ -225,9 +223,7 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( throw new IllegalStateException("Membership lifecycle does not allow JOIN"); } FirstJoinEvidence current = readCurrentJoinEvidence(scope, membership, roles, checkpoint); - if ("PENDING".equals(operation.status()) - && "ALREADY_ACTIVE".equals(outcome) - && requestId.equals(current.event().requestId())) { + if ("ALREADY_ACTIVE".equals(outcome) && requestId.equals(current.event().requestId())) { throw new IllegalStateException("Pending JOIN cannot adopt its precommitted transition"); } if ("JOINED".equals(outcome) && !requestId.equals(current.event().requestId())) { @@ -252,16 +248,11 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( String payload = canonicalCurrentAuditPayload(scope, requestId, operation, current, checkpoint); UUID auditId = auditEventIdFor(requestId); - AccountAuditEnvelope audit; - if ("PENDING".equals(operation.status())) { - AccountAuditEnvelope appended = - auditOutboxRepository.appendCanonicalTenant( - auditId, scope.tenantId().toString(), JOINED_EVENT_TYPE, payload); - audit = - auditOutboxRepository.findExactCanonicalTenantEnvelopeForUpdate(appended).orElseThrow(); - } else { - audit = auditOutboxRepository.findCanonicalTenantEnvelopeForUpdate(auditId).orElseThrow(); - } + AccountAuditEnvelope appended = + auditOutboxRepository.appendCanonicalTenant( + auditId, scope.tenantId().toString(), JOINED_EVENT_TYPE, payload); + AccountAuditEnvelope audit = + auditOutboxRepository.findExactCanonicalTenantEnvelopeForUpdate(appended).orElseThrow(); requireExactAudit(audit, scope, auditId, payload, operation.terminalProof()); proof = proof(operation, current, audit); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index fd7a46a759..bec8508228 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -191,7 +191,13 @@ private Caller verifyDirectCaller( return inTransaction( () -> { requireDirectPeer(); - Account account = accounts.findByAccountUuidForUpdate(context.accountId()).orElseThrow(); + Account account = + accounts + .findByAccountUuidForUpdate(context.accountId()) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller Account is unknown")); if (account.getId() == null || account.getId() <= 0L || !context.accountId().equals(account.getAccountUuid()) diff --git a/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql b/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql index 60b5dc9b61..d39f798333 100644 --- a/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql +++ b/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql @@ -319,7 +319,7 @@ BEGIN END IF; IF NEW.status IS DISTINCT FROM 'COMMITTED' - OR NEW.outcome NOT IN ('JOINED', 'ALREADY_ACTIVE') + OR NEW.outcome IS NULL OR NEW.outcome NOT IN ('JOINED', 'ALREADY_ACTIVE') OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' OR (NEW.outcome = 'JOINED' AND NEW.allow_public_join IS DISTINCT FROM TRUE) OR NEW.allow_public_join IS NULL diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index d1c6fea38a..69f0cec8df 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -348,6 +348,50 @@ void activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays() { }); } + @Test + void nullCommittedOutcomeIsRejectedByTerminalReceiptShapeGuard() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + String nextRequest = fixture.prepareAnotherJoin(); + + // Retain a valid current membership witness but omit only the required committed outcome. + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.dsl.execute( + """ + UPDATE account_join_operations pending + SET status = 'COMMITTED', outcome = NULL, + last_attempt_authority_availability = 'AVAILABLE', + membership_id = original.membership_id, + outcome_membership_version = original.outcome_membership_version, + outcome_membership_authority_generation = original.outcome_membership_authority_generation, + membership_authority_outbox_stream_key = original.membership_authority_outbox_stream_key, + membership_authority_outbox_sequence = original.membership_authority_outbox_sequence, + membership_authority_event_id = original.membership_authority_event_id, + membership_authority_event_digest = original.membership_authority_event_digest + FROM account_join_operations original + WHERE pending.request_id = ? AND original.request_id = ? + """, + nextRequest, + fixture.requestId))) + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains("Canonical JOIN terminal receipt is incomplete or noncommitting"); + }); + + var committed = fixture.commitExistingJoin(nextRequest); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.outcome()).isEqualTo("ALREADY_ACTIVE"); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + @Test void closingEnrollmentPreservesAnActiveMembersEventFreeJoinSnapshot() { Fixture fixture = newFixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index a395c0af0f..edef33bdaf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -285,6 +285,17 @@ void inactiveJoinRestoresOnlyPlayerWithoutRegrantingRetainedElevatedRoles( fixture.scope, REQUEST_ID, CALLER_BINDING, null, null, null); assertThat(result).isSameAs(committed); + verify(fixture.eventProducer) + .requireCurrentCanonicalJoinPolicy( + fixture.scope, fixture.operation, true, null, null, null); + verify(fixture.audit) + .appendCanonicalTenant( + fixture.expectedProof.auditEventId(), + TENANT_ID.toString(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + fixture.auditPayload); + verify(fixture.audit).findExactCanonicalTenantEnvelopeForUpdate(fixture.auditEnvelope); + verify(fixture.audit, never()).findCanonicalTenantEnvelopeForUpdate(any()); InOrder ordered = inOrder(fixture.roles, fixture.eventProducer); ordered .verify(fixture.roles) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 78e4a0937b..9bb34691ce 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -136,6 +136,46 @@ void directProducerRefusesWrongPeerBeforeReadingAccountOrSources(String mismatch f.entitlements); } + @Test + void directProducerRejectsUnknownAccountWithoutReadingTargetsOrPersistingScope() { + Fixture f = new Fixture(300000L); + doReturn(Optional.empty()).when(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "CONNECT_CONTEXT_INVALID", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + + verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + verifyNoInteractions( + f.memberships, f.tenants, f.heads, f.scopes, f.sessions, f.targets, f.entitlements); + } + + @Test + void directProducerKeepsAccountRepositoryFailureRetryableWithoutReadingTargets() { + Fixture f = new Fixture(300000L); + doThrow(new IllegalStateException("Account repository unavailable")) + .when(f.accounts) + .findByAccountUuidForUpdate(ACCOUNT); + + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + + verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + verifyNoInteractions( + f.memberships, f.tenants, f.heads, f.scopes, f.sessions, f.targets, f.entitlements); + } + @Test void directProducerReportsUnavailableEntitlementWithoutMisclassifyingThePointer() { Fixture f = new Fixture(300000L); From 2a79254d43bc2f5e6d25fca7a34a00a2959a30b0 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 00:39:33 +1300 Subject: [PATCH 39/66] Align wallet settlement fixture and isolate JOIN proof boundaries --- ...iptionDispatchPostgresIntegrationTest.java | 53 +++++++++++++----- ...tJoinOperationRepositoryCanonicalTest.java | 55 ++++++++++++++++++- 2 files changed, 92 insertions(+), 16 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index 69dfce3ab4..d1fcb8ae4e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -624,14 +624,39 @@ void displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDea } @Test - void displayRefreshDoesNotAuthorizeInitialClaimOrDirectDispatchInsert() { - Fixture unclaimed = fixture("1032"); + void displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch() { + Fixture unclaimed = fixture(null); refreshDisplay(unclaimed); - assertThatThrownBy(() -> claim(unclaimed, 1)).isInstanceOf(FenceRejectedException.class); - assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_work"))).isZero(); + var refused = + unclaimed + .tx() + .execute( + s -> + unclaimed + .owner() + .claim(unclaimed.creation().requestId(), 1, UUID.randomUUID())); + assertThat(Objects.requireNonNull(refused).disposition()) + .isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(refused.claim()).isNull(); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_work"))).isOne(); + assertThat( + Objects.requireNonNull( + unclaimed.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) + .intoMap()) + .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") + .containsEntry("failure_reason", "RESERVED_INSTRUMENT_CHANGED"); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) + .isOne(); assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))) .isZero(); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) + .isZero(); + assertThat(unclaimed.transport().creates).isZero(); + assertThat(unclaimed.transport().searches).isZero(); + } + @Test + void displayRefreshDoesNotAuthorizeDirectDispatchInsert() { Fixture retained = fixture("1032"); var original = claim(retained, 1); refreshDisplay(retained); @@ -996,15 +1021,17 @@ private static T in(TransactionTemplate tx, java.util.function.Supplier a } private static void migrate(DriverManagerDataSource source, String schema, String target) { - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration", "classpath:db/migration/saga") - .target(target) - .load() - .migrate(); + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); } private record Fixture( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java index 223917f24c..9b297e414a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -46,6 +46,36 @@ void terminalProofRetainsLaterMembershipEventAndRevisionWithoutClaimingFirstJoin // Actual first-JOIN writes retain their distinct exact 1/2/1 repository and SQL checks. } + @Test + void firstJoinRejectsNonFirstEventSequenceBeforeOwnerStorageReads() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + var repository = new AccountJoinOperationRepository(dsl, scopes); + + assertThatThrownBy( + () -> + repository.commitCanonicalFirstJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(2L, 2L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact first-JOIN terminal proof required"); + verifyNoInteractions(dsl, scopes); + } + + @Test + void firstJoinRejectsNonFirstMembershipRevisionBeforeOwnerStorageReads() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + var repository = new AccountJoinOperationRepository(dsl, scopes); + + assertThatThrownBy( + () -> + repository.commitCanonicalFirstJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(1L, 3L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact first-JOIN terminal proof required"); + verifyNoInteractions(dsl, scopes); + } + @Test void terminalProofRejectsNonpositiveEventOrMembershipRevision() { assertThatThrownBy(() -> proof(0L, 2L)).isInstanceOf(IllegalArgumentException.class); @@ -117,8 +147,27 @@ void failedEvidenceMayRetainPolicyButCannotCarrySuccessProofOrRetryableOutcome() /** Controlled journal content, not caller authentication or entitlement source evidence. */ @Test void committedNullOutcomeIsClassifiedAsInconsistentTerminalEvidence() { + var proof = validProof(); + var proofWithoutAudit = + new CanonicalJoinTerminalProof( + proof.eventStreamKey(), + proof.eventSequence(), + proof.eventId(), + proof.eventDigest(), + null, + null, + null, + proof.entitlementVersion(), + proof.membershipId(), + proof.membershipVersion(), + proof.membershipAuthorityGeneration()); + assertThat(evidence(true, "COMMITTED", "JOINED", "AVAILABLE", null, proof, 73L)).isNotNull(); + assertThat( + evidence( + true, "COMMITTED", "ALREADY_ACTIVE", "AVAILABLE", null, proofWithoutAudit, 73L)) + .isNotNull(); assertThatThrownBy( - () -> evidence(true, "COMMITTED", null, "AVAILABLE", null, validProof(), 73L)) + () -> evidence(true, "COMMITTED", null, "AVAILABLE", null, proofWithoutAudit, 73L)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Canonical JOIN terminal evidence is inconsistent"); } @@ -219,8 +268,8 @@ private static CanonicalJoinOperationEvidence evidence( status, outcome, membershipId, - null, - null, + proof == null ? null : proof.membershipVersion(), + proof == null ? null : proof.membershipAuthorityGeneration(), proof, retained); } From 16e010d9d6ee2437598c84a36b149db7065d5f01 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 01:08:13 +1300 Subject: [PATCH 40/66] Split provider execution and expanded receiving proof behind canonical Account cutover --- .../player-access-and-session.md | 20 +- .../StripeHostingSubscriptionProvisioner.java | 243 -- ...ostingSubscriptionLifecycleRepository.java | 137 +- .../AccountSubscriptionIntentRepository.java | 21 +- ...ostingSubscriptionProvisioningService.java | 138 -- ...alJoinScopePersistenceIntegrationTest.java | 653 ------ ...iptionDispatchPostgresIntegrationTest.java | 1222 ---------- ...ptionLifecyclePostgresIntegrationTest.java | 1989 ----------------- ...criptionIntentPostgresIntegrationTest.java | 1883 ---------------- ...ourceSelectionPostgresIntegrationTest.java | 350 --- ...anonicalFirstJoinEventIntegrationTest.java | 1167 +--------- ...nicalFirstJoinPostgresIntegrationTest.java | 399 ---- ...titlementOwnerPostgresIntegrationTest.java | 329 --- ...ionCompositionPostgresIntegrationTest.java | 587 ----- ...ipeHostingSubscriptionProvisionerTest.java | 478 ---- ...ngSubscriptionLifecycleRepositoryTest.java | 37 +- ...ngSubscriptionProvisioningServiceTest.java | 199 -- ...untRuntimeStubServerCompatibilityTest.java | 408 +--- .../test/AccountRuntimeStubServer.java | 149 +- ...ationOwnerCompositionCrossServiceTest.java | 162 +- ...PlayerAdmissionEntitlementComposition.java | 272 --- ...ldPublishedAdmissionSourceCleanupTest.java | 112 - ...ldPublishedAdmissionSourceComposition.java | 273 --- 23 files changed, 140 insertions(+), 11088 deletions(-) delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java delete mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java delete mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java delete mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 15778e7116..938b854ad5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,7 +24,7 @@ This is an intentionally breaking preproduction format cutover of the manually c ### Receiving review boundaries -PR #3389 now carries the independent Account source/transport foundation on the supported `develop` runtime. Its unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery do not replace live PLAY authority. This draft PR #3390 retains canonical UUID schema retirement, the public facade/JOIN receiving cutover, initial hosting provider-write source with its focused units, and dependent physical proof; it remains unfinished until a functioning canonical PLAY replacement is qualified. PR #3403 retains private FRESH/World preparation. The source and prior corrections remain preserved through normal ancestry; the changed comparisons do not reset review counts or grant current coverage. No new caller custody, runtime registration, admission or activation is established by the reconstruction. +PR #3389 now carries the independent Account source/transport foundation on the supported `develop` runtime. Its unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery do not replace live PLAY authority. This draft PR #3390 retains canonical UUID schema retirement, the public facade/JOIN receiving cutover, the schema/retention foundation and focused owner units; provider-write execution and expanded dependent physical proof move to the immediate successor; it remains unfinished until a functioning canonical PLAY replacement is qualified. PR #3403 retains private FRESH/World preparation. The source and prior corrections remain preserved through normal ancestry; the changed comparisons do not reset review counts or grant current coverage. No new caller custody, runtime registration, admission or activation is established by the reconstruction. ### Controlled player-admission transport composition @@ -34,25 +34,15 @@ A further prepared [committed-LOGIN composition](../../../services/account-servi ### Canonical billing and retention receiving -The receiving foundation retains numeric subscription rows in the original renamed heap as immutable, non-authorizing evidence (V1028), installs canonical UUID subscription intent/provider history (V1029), and retains complete provisioning/lifecycle schema (V1030), first-dispatch claims (V1032) and cancellation-resolution journals (V1036). Retained history remains useful only for conservative deletion blockers; it is never current entitlement authority. The manually composed cancellation component keeps actual Account actor/authentication and owner-local atomic receipt/fence/event checks and prepares one allowed safe outcome. Historical coupled 356 physical proof passed through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit; the later exact-head failures and replacement-proof limits below qualify that retained history. Its five PostgreSQL/AOF-replica cases cover atomic row/CAS/journal/receipt/audit/billing/tenant-event completion, canonical canceled current-read recovery, immutable failed history, authenticated replay, wrong credentials, late SQL rollback with restored OTP, authority change during the SDK read, and another Account's credential refusal. Enabled integration/test-fixture analysis and formatting pass. Unchanged 355 regression passes 20 lifecycle and 21 original-order cases; its original aggregate retains the corrected error-code expectation failure. These qualify the prepared cancellation component, with controlled policy/signer and Stripe transport inputs, and do not establish production custody or runtime registration. Provider absence and transfer are separate outcomes; production/default registration remains held and is not a prerequisite to qualifying this unregistered component boundary. +This Account cutover retains the original numeric subscription heap as immutable, non-authorizing history (V1028), installs the canonical UUID subscription intent/provider-history, provisioning, first-dispatch, terminal-resolution and wallet-settlement schema (V1029/V1030/V1032/V1036/V1039), and moves retention/deletion reads to the dedicated historical-evidence repository. The old numeric entitlement reader and demo subscription seeder are removed together. Numeric runtime entitlement requests fail closed; no canonical entitlement is inferred from retained rows. -The physical Account partitions from run `42329363290` at merge `db84cabe83ab93dc0aac28f359a3f359cd52bfd6` for published `3adbf512` expose four stale assertions; their failures remain retained. The corrected [lifecycle fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java) separates an unresolved first `past_due` observation without retained episode origin from effective cancellation starting at a valid active receipt. The unresolved case requires `RECONCILING` / `RECOVERY_ORIGIN_UNRESOLVED`, unchanged prior receipt and authority, no new positive event and a held instrument reservation. Genuine `past_due` → `grace` → `suspended` physical coverage still requires an authoritative retained episode origin and is not established by this correction; Account owns that positive proof obligation before recovery-lifecycle qualification. The independent cancellation case retains monotonic cutoff, replacement refusal and reservation release only after confirmed provider cancellation. The [currentness fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java) uses a supported `active` → `canceled` transition to preserve checkpoint, replay, monotonic authority/event, realm-grant tombstone and direct-SQL reactivation-refusal assertions without claiming `past_due` coverage. The [dispatch fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java) now expects the earlier typed original-binding fence after replacement, with unchanged durable row images and no provider create. The [terminal composition fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java) now expects typed source unavailability after a real generic Account authority/fence advance, preserving unchanged financial/failure evidence and an unconsumed OTP; that generic event does not prove a supported current-actor mismatch branch. Production policy, fence ordering and closed source-event families remain unchanged. The reconstructed source and these four corrections pass affected Account production/unit/integration compilation, enabled Account static analysis, World cross-service compilation, Java formatting and documentation checks. The same locked local gate passed all 39 focused Game Session discovery cases and 18 codec cases in 7m26s. The four PostgreSQL corrections were compiled, not executed locally; replacement physical proof remains outstanding and no runtime Smoke pass is claimed for this unfinished cutover. +The immediate successor owns the initial Stripe provider-write adapter and provisioning composition, the unclaimed-wallet settlement repository refinements, their focused unit and native PostgreSQL proof, and expanded World/stub receiving compositions. Those source and proof obligations are preserved in the original #3390 history and the complete successor tree. Their earlier source-specific proof is not proof of this reduced parent. Required physical migration, fresh-image runtime and exact-head CI qualification remain separate from local source compilation and focused units. -Account deletion remains held. Its conservative billing-owner precondition currently inspects only retained numeric subscription history; it does not yet read nonterminal canonical UUID subscriptions owned by the Account. After the earlier retained-JOIN blocker is clear, a canonical-only billing owner therefore receives `ACCOUNT_DELETE_UNAVAILABLE`, not the required `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER`. The deletion owner must qualify that canonical current-owner check and positive/negative proof before deletion can be enabled, while preserving retained-history blockers and the [Account deletion contract](../../architecture/microservices/account-service/api-contracts.md). No deletion or billing-owner release is enabled by this foundation. - -This receiver owns the [Stripe provisioner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java), [provisioning composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java), their [adapter units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java) and [composition units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java), and the existing [dispatch physical suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java). Removing those four inherited source/unit files from #3389 preserves their bytes here alongside the canonical storage and dependent physical proof. This is an ownership transfer, not new payment support or qualification; both components remain manually composed and unregistered, with the authenticated create producer, provider worker and public billing route held. - -The paid first-invoice confirmation finding remains open in this receiving boundary. Stripe `default_incomplete` creation and subscription polling do not confirm a required first payment; the negative adapter unit checks that incomplete results remain non-authorizing, while the dispatch physical suite uses controlled active-subscription inputs rather than live paid-checkout proof. Complete confirmation through the accepted Account/provider-hosted checkout boundary after confirmed provider linkage, preserving [ADR 0044](../../architecture/decisions/adr-0044-account-owned-payment-instruments-with-explicit-subscription-binding.md) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); do not enable automatic charging inside the held provisioning adapter. No finding closure, runtime registration or activation is established by moving the source and proof together. - -The current billing-owner tuple deliberately rejects unaudited updates. Fixture reconciliation preserves that refusal and unchanged row/xmin, stale owner version/generation capture refusal, and genuine payment-instrument advancement concurrency. Positive queued-create fencing after a real audited owner-transfer commit remains an obligation of the unimplemented transfer owner; constructed stale comparison inputs do not prove that transfer. - -The same receiving boundary carries the distinct TENANT_OPERATION evidence, Account source/peer-qualified receiver, and World client/mTLS proof. These are unregistered source components, with controlled upstream/PKI limitations. Receiving compilation 328 passes. Focused 331 executes 203 Account units, nine shared evidence/transport cases, four actual World→Account mTLS cases and 80 PostgreSQL cases; its aggregate fails two intent fixtures. Corrected 336 passes all 20 intent cases (including the additional unaudited-update refusal), enabled affected static checks, formatting and documentation. Together these executions establish 81 unique focused PostgreSQL cases without failures/errors/skips; unchanged passing suites retain 331 attribution. Fresh-image/runtime and current-head CI/review remain required; controlled sources/PKI do not establish production custody or authenticated transfer. - -The earlier published #3389 comparison deliberately left public facade and numeric runtime entitlement paths unavailable; its historical source-built340 run passed held-edge denial and LOGIN but failed PLAY with ENTITLEMENT_UNAVAILABLE. Authenticated teardown and independently empty resources passed. This remains incomplete runtime qualification for that historical comparison, not a passing smoke result or a description of the reconstructed #3389 foundation, which preserves the supported parent runtime. The complete public consumer receiving below restores its own supported canonical compositions; canonical runtime cutover and final functional restoration remain separate obligations. Ordinary UUID identity/profile/retention protections retain their focused proof. +Account deletion remains held. Its conservative billing-owner precondition inspects retained numeric history, not nonterminal canonical UUID subscriptions. No provider worker, billing mutation route, player admission or production activation is enabled by this split. ### Canonical public Account facade receiving -The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). +The parent source restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). Preserved source proof 310 passes 575 selected Account units; proof 318 passes 312 facade units and two actual HTTP→Entity compositions; proof 320 passes 42 App PostgreSQL cases; proof 321 passes 13 first-JOIN cases; proof 324 passes 22 PLAYER_ADMISSION owner cases plus five shared cases; and proof 335 passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation 342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving proofs 343/345 establish 793 unique selected unit passes after correcting one obsolete first-only generic proof assertion; proof 351 passes 169 selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest in proof 346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main proof 198/200 holds remain. Remaining proof 347 static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused transport proof 352 passes all 34 mTLS client cases (31 new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. Published #3390 carries this public source; the terminal-cancellation finding is independently qualified by the coupled composition 356 in #3389. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java deleted file mode 100644 index f491949494..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java +++ /dev/null @@ -1,243 +0,0 @@ -package net.firedevops.firemud.accountservice.client; - -import com.stripe.exception.StripeException; -import com.stripe.model.StripeSearchResult; -import com.stripe.model.Subscription; -import com.stripe.net.RequestOptions; -import com.stripe.param.SubscriptionCreateParams; -import com.stripe.param.SubscriptionListParams; -import com.stripe.param.SubscriptionSearchParams; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.time.Clock; -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Held initial hosting-subscription SDK adapter. Only a private, independently read durable owner - * dispatch supplies its explicit customer, instrument, quote and initial-call permission. Existing - * or pre-migration unknown dispatches reconcile only; no empty search authorizes recreation. No - * actor authorization, update/cancel command, runtime registration or entitlement is supplied. - */ -public final class StripeHostingSubscriptionProvisioner { - private static final long MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER = 100L; - - private final com.stripe.StripeClient stripe; - private final Clock clock; - private final RequestOptions requestOptions; - private final StripeHostingSubscriptionObserver observer; - private final StripeBillingPrerequisiteObserver prerequisites; - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = - "Injected SDK/repository collaborators remain private; copying would break owner composition.") - public StripeHostingSubscriptionProvisioner( - com.stripe.StripeClient stripe, - Clock clock, - boolean expectedLivemode, - Duration connectTimeout, - Duration readTimeout) { - this.stripe = Objects.requireNonNull(stripe); - this.clock = Objects.requireNonNull(clock); - observer = new StripeHostingSubscriptionObserver(stripe, clock, connectTimeout, readTimeout); - // The observer validates positive whole-millisecond SDK limits before this conversion. - requestOptions = - RequestOptions.builder() - .setConnectTimeout(Math.toIntExact(connectTimeout.toMillis())) - .setReadTimeout(Math.toIntExact(readTimeout.toMillis())) - .setMaxNetworkRetries(0) - .build(); - prerequisites = new StripeBillingPrerequisiteObserver(stripe, clock, expectedLivemode); - } - - public Result provision(ProviderDispatch dispatch) { - Objects.requireNonNull(dispatch); - requireNoTransaction(); - if (!dispatch.readyForProviderIo()) { - throw new IllegalStateException( - "Committed independent provider-dispatch readback is required"); - } - if (!live(dispatch)) { - return new Pending("DISPATCH_LEASE_EXPIRED", null); - } - var creation = dispatch.claim().creation(); - // Local reservations do not prove that the provider's instrument is still attached. - var prerequisite = - prerequisites.observe( - new StripeBillingPrerequisiteObserver.ExpectedBinding( - creation.owner().accountUuid(), - creation.customerProvisioningRequestId(), - dispatch.customerProviderIdempotencyId(), - creation.providerCustomerId(), - dispatch.providerPaymentMethodId()), - requestOptions); - if (!(prerequisite instanceof StripeBillingPrerequisiteObserver.ObservedBillingPrerequisites)) { - return new Pending("PROVIDER_PREREQUISITES_UNRESOLVED", null); - } - if (!live(dispatch)) { - return new Pending("DISPATCH_LEASE_EXPIRED", null); - } - Map metadata = - Map.of( - "firemud_metadata_schema_version", - "1", - "firemud_operation_type", - "subscription_provisioning", - "firemud_operation_id", - creation.subscriptionProvisioningRequestId().toString(), - "firemud_subscription_id", - creation.subscriptionId().toString()); - try { - String query = - "metadata['firemud_metadata_schema_version']:'1' AND " - + "metadata['firemud_operation_type']:'subscription_provisioning' AND " - + "metadata['firemud_operation_id']:'" - + creation.subscriptionProvisioningRequestId() - + "' AND metadata['firemud_subscription_id']:'" - + creation.subscriptionId() - + "'"; - StripeSearchResult matches = - stripe - .subscriptions() - .search( - SubscriptionSearchParams.builder().setQuery(query).setLimit(2L).build(), - requestOptions); - if (matches == null - || matches.getData() == null - || !Boolean.FALSE.equals(matches.getHasMore()) - || matches.getData().size() > 1) { - return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_SEARCH", null); - } - Subscription candidate; - if (matches.getData().isEmpty()) { - if (!dispatch.initialCallAllowed()) { - if (!live(dispatch)) { - return new Pending("DISPATCH_LEASE_EXPIRED", null); - } - var listed = - stripe - .subscriptions() - .list( - SubscriptionListParams.builder() - .setCustomer(creation.providerCustomerId()) - .setStatus(SubscriptionListParams.Status.ALL) - .setLimit(MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) - .build(), - requestOptions); - if (listed == null - || listed.getData() == null - || !Boolean.FALSE.equals(listed.getHasMore()) - || listed.getData().size() > MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) { - return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); - } - candidate = null; - for (Subscription listedCandidate : listed.getData()) { - if (listedCandidate == null) { - return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); - } - if (metadata.equals(listedCandidate.getMetadata())) { - if (!creation.providerCustomerId().equals(listedCandidate.getCustomer())) { - return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); - } - if (candidate != null) { - return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); - } - candidate = listedCandidate; - } - } - if (candidate == null) { - return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null); - } - } else { - if (!live(dispatch)) { - return new Pending("DISPATCH_LEASE_EXPIRED", null); - } - candidate = - stripe - .subscriptions() - .create( - SubscriptionCreateParams.builder() - .setCustomer(creation.providerCustomerId()) - .setDefaultPaymentMethod(dispatch.providerPaymentMethodId()) - .setCollectionMethod( - SubscriptionCreateParams.CollectionMethod.CHARGE_AUTOMATICALLY) - .setPaymentBehavior( - SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE) - .addItem( - SubscriptionCreateParams.Item.builder() - .setPrice(creation.planQuote().providerPriceId()) - .setQuantity(creation.planQuote().providerQuantity()) - .build()) - .putAllMetadata(metadata) - .build(), - requestOptions - .toBuilderFullCopy() - .setIdempotencyKey( - creation.subscriptionProvisioningRequestId().toString()) - .build()); - } - } else { - candidate = matches.getData().getFirst(); - } - // Candidate status is never authority. Exact identity and metadata only select readback. - if (candidate == null - || !"subscription".equals(candidate.getObject()) - || candidate.getId() == null - || !candidate.getId().matches("sub_[A-Za-z0-9]{1,251}") - || !metadata.equals(candidate.getMetadata())) { - return new Pending("PROVIDER_CANDIDATE_BINDING_INVALID", null); - } - if (!live(dispatch)) { - return new Pending("DISPATCH_LEASE_EXPIRED", null); - } - var observed = observer.observe(dispatch.expectedBinding(candidate.getId())); - if (!(observed instanceof StripeHostingSubscriptionObserver.ObservedSubscription actual)) { - return new Pending("INDEPENDENT_PROVIDER_READBACK_UNRESOLVED", null); - } - return new Located(actual); - } catch (StripeException failure) { - return new Pending("PROVIDER_OUTCOME_UNKNOWN", failure); - } - } - - private boolean live(ProviderDispatch dispatch) { - var now = clock.instant(); - return !now.isBefore(dispatch.claim().claimedAt()) - && now.isBefore(dispatch.claim().expiresAt()); - } - - private static void requireNoTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("Hosting provider IO refuses an ambient SQL transaction"); - } - } - - public sealed interface Result permits Pending, Located {} - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = - "The SDK exception is an internal diagnostic cause, never provider authority or a public response.") - public record Pending(String reason, StripeException providerFailure) implements Result {} - - /** Locator plus genuine private observer evidence; lifecycle commit independently reads again. */ - public static final class Located implements Result { - private final StripeHostingSubscriptionObserver.ObservedSubscription observation; - - private Located(StripeHostingSubscriptionObserver.ObservedSubscription observation) { - this.observation = observation; - } - - public StripeHostingSubscriptionObserver.ObservedSubscription observation() { - return observation; - } - - public String providerSubscriptionId() { - return observation.providerSubscriptionId(); - } - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index c8642ee88c..4ce8feca92 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -1215,20 +1215,24 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId } long versionToLock = prior == null ? expectedRowVersion : prior.get("claimed_row_version", Long.class); - AccountSubscriptionCurrentRecord current; - try { - current = intents.lockForProvisioningRecovery(requestId, versionToLock); - } catch (FenceRejectedException refused) { - // A later wallet observation may prevent even the first dispatch. The original intent - // can use the local settlement fence, but this path never returns a provider-capable claim. - return recoverUndispatchableWork(requestId, versionToLock, prior); - } + var current = intents.lockForProvisioningRecovery(requestId, versionToLock); var original = intents.findCreation(requestId).orElseThrow(); Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); if (now.isBefore(original.createdAt())) { throw new FenceRejectedException("Provisioning clock predates the durable intent"); } - retainUnclaimedWork(original); + dsl.execute( + "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " + + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + requestId, + original.subscriptionId(), + limits.maximumAttempts(), + limits.maximumStalledAttempts(), + limits.lease().toMillis(), + limits.backoff().toMillis(), + utc(original.createdAt().plus(limits.absoluteTimeout())), + utc(original.createdAt())); Record work = workForUpdate(requestId); if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { return new ClaimResult(Disposition.TERMINAL_FAILURE, null); @@ -1313,93 +1317,6 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId return new ClaimResult(Disposition.CLAIMED, claim(original, Objects.requireNonNull(attempt))); } - private void retainUnclaimedWork(AccountSubscriptionCreationRecord original) { - dsl.execute( - "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " - + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " - + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", - original.requestId(), - original.subscriptionId(), - limits.maximumAttempts(), - limits.maximumStalledAttempts(), - limits.lease().toMillis(), - limits.backoff().toMillis(), - utc(original.createdAt().plus(limits.absoluteTimeout())), - utc(original.createdAt())); - } - - private ClaimResult recoverUndispatchableWork(UUID requestId, long version, Record prior) { - var current = intents.lockForProvisioningSettlement(requestId, version); - var original = intents.findCreation(requestId).orElseThrow(); - Instant now = now(); - if (now.isBefore(original.createdAt())) { - throw new FenceRejectedException("Provisioning clock predates the durable intent"); - } - retainUnclaimedWork(original); - Record work = workForUpdate(requestId); - if (work.get("last_attempt_id") == null) { - if (prior != null - || work.get("attempt_count", Integer.class) != 0 - || !current.subscriptionId().equals(work.get("subscription_id", UUID.class)) - || !"pending".equals(current.status()) - || current.rowVersion() != 1L - || current.providerSubscriptionId() != null - || links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { - throw new FenceRejectedException("Exact unclaimed provisioning settlement fence rejected"); - } - if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { - return new ClaimResult(Disposition.TERMINAL_FAILURE, null); - } - if (!"RECONCILING".equals(work.get("phase", String.class))) { - throw new FenceRejectedException("Unclaimed provisioning work is not reconciling"); - } - // No claim is issued and no provider absence is inferred. Keep the reservation held and - // retain one operator item even when the wallet changed before work was first claimed. - return fail(work, "RESERVED_INSTRUMENT_CHANGED", now); - } - requireUnmappedProvisioningWork(current, work); - if (prior != null - && !prior.get("attempt_id", UUID.class).equals(work.get("last_attempt_id", UUID.class))) { - return new ClaimResult(Disposition.ATTEMPT_EXPIRED, null); - } - Record retained = - dsl.fetchOne( - "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", - work.get("last_attempt_id", UUID.class)); - if (retained == null || now.isBefore(instant(retained, "claimed_at"))) { - throw new FenceRejectedException("Exact retained provisioning attempt is absent or future"); - } - if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { - return new ClaimResult(Disposition.TERMINAL_FAILURE, null); - } - if (!now.isBefore(instant(work, "deadline_at"))) { - return fail(work, "ABSOLUTE_DEADLINE", now); - } - if ("CLAIMED".equals(work.get("phase", String.class)) - && now.isBefore(instant(work, "lease_expires_at"))) { - return new ClaimResult(Disposition.WAITING, null); - } - if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { - return fail(work, "ATTEMPT_BUDGET", now); - } - if (work.get("attempt_count", Integer.class) - >= work.get("max_stalled_attempts", Integer.class)) { - return fail(work, "STALLED_WITHOUT_COMMITTED_PROGRESS", now); - } - return new ClaimResult(Disposition.WAITING, null); - } - - private void requireUnmappedProvisioningWork( - AccountSubscriptionCurrentRecord current, Record work) { - if (!current.subscriptionId().equals(work.get("subscription_id", UUID.class)) - || !Objects.equals(current.rowVersion(), work.get("subscription_row_version", Long.class)) - || work.get("last_attempt_id") == null - || current.providerSubscriptionId() != null - || links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { - throw new FenceRejectedException("Exact unmapped retained provisioning work fence rejected"); - } - } - /** * Inserts a separate immutable provider-dispatch boundary after revalidating the exact live * private worker claim. Only a newly inserted first-dispatch receipt may carry initial-call @@ -1637,27 +1554,9 @@ public ExpectedBinding expectedBinding(String providerId) { public Disposition deferUnresolved(ProvisioningClaim claim) { requireTransaction(); Objects.requireNonNull(claim); - var current = - intents.lockForProvisioningSettlement( - claim.creation().requestId(), claim.subscriptionRowVersion()); + intents.lockForProvisioningRecovery( + claim.creation().requestId(), claim.subscriptionRowVersion()); Record work = workForUpdate(claim.creation().requestId()); - requireUnmappedProvisioningWork(current, work); - Record retained = - dsl.fetchOne( - "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", - claim.attemptId()); - if (retained == null - || !claim - .creation() - .equals(intents.findCreation(claim.creation().requestId()).orElseThrow()) - || !claim.creation().requestId().equals(retained.get("request_id", UUID.class)) - || !claim.creation().subscriptionId().equals(retained.get("subscription_id", UUID.class)) - || claim.attemptNumber() != retained.get("attempt_number", Integer.class) - || claim.subscriptionRowVersion() != retained.get("claimed_row_version", Long.class) - || !claim.claimedAt().equals(instant(retained, "claimed_at")) - || !claim.expiresAt().equals(instant(retained, "expires_at"))) { - throw new FenceRejectedException("Exact retained provisioning settlement claim rejected"); - } Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); if (now.isBefore(claim.claimedAt())) { throw new FenceRejectedException("Provisioning clock predates its retained claim"); @@ -1669,12 +1568,12 @@ public Disposition deferUnresolved(ProvisioningClaim claim) { if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(phase)) { return Disposition.TERMINAL_FAILURE; } - if (!now.isBefore(instant(work, "deadline_at"))) { - return fail(work, "ABSOLUTE_DEADLINE", now).disposition(); - } if ("RECONCILING".equals(phase)) { return Disposition.WAITING; } + if (!now.isBefore(instant(work, "deadline_at"))) { + return fail(work, "ABSOLUTE_DEADLINE", now).disposition(); + } if (!now.isBefore(claim.expiresAt())) { // The exact retained attempt expired without a provider completion. Leave its work and // reservation untouched for the next claimant rather than treating normal expiry as a fault. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java index f92bedbf5f..a453192439 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java @@ -212,29 +212,16 @@ public AccountSubscriptionCurrentRecord lockForProvisioningRecovery( */ public AccountSubscriptionCurrentRecord lockForLifecycle( UUID requestId, long expectedRowVersion) { - return lockBinding(requestId, expectedRowVersion, true, true, true); - } - - /** - * Local settlement only for retained provisioning work. Later wallet observations cannot strand - * its original reservation, but this lock never authorizes a claim or provider dispatch. - */ - AccountSubscriptionCurrentRecord lockForProvisioningSettlement( - UUID requestId, long expectedRowVersion) { - return lockBinding(requestId, expectedRowVersion, true, false, true); + return lockBinding(requestId, expectedRowVersion, true, true); } private AccountSubscriptionCurrentRecord lockProvisioningBinding( UUID requestId, long expectedRowVersion, boolean allowProvisioning) { - return lockBinding(requestId, expectedRowVersion, allowProvisioning, false, false); + return lockBinding(requestId, expectedRowVersion, allowProvisioning, false); } private AccountSubscriptionCurrentRecord lockBinding( - UUID requestId, - long expectedRowVersion, - boolean allowProvisioning, - boolean lifecycle, - boolean allowInstrumentObservation) { + UUID requestId, long expectedRowVersion, boolean allowProvisioning, boolean lifecycle) { requireWritableTransaction(); AccountBillingCustomerRecord.requireUuid(requestId); if (expectedRowVersion < 1) { @@ -252,7 +239,7 @@ private AccountSubscriptionCurrentRecord lockBinding( currentForUpdate(original.tenantId()) .orElseThrow(() -> new FenceRejectedException("Current subscription is absent")); boolean instrumentVersionAndStateMatch = - allowInstrumentObservation + lifecycle ? instrument.rowVersion() >= original.reservedInstrumentVersion() && (instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE || instrument.state() == AccountPaymentInstrumentRecord.State.UNAVAILABLE) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java deleted file mode 100644 index cf2ecd7076..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.firedevops.firemud.accountservice.service; - -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Held owner composition for an existing genuine private provisioning claim. This does not admit - * CreateSubscription callers or register any bean/route/worker. The authenticated create producer, - * production custody and deployment remain held. Dispatch commits and independent owner readback - * precede provider IO; provider output cannot directly write status or confer entitlement. Existing - * lifecycle reconciliation performs its own SDK read, fenced commit, then independent current read. - */ -public final class AccountHostingSubscriptionProvisioningService { - private final AccountHostingSubscriptionLifecycleRepository repository; - private final StripeHostingSubscriptionProvisioner provider; - private final AccountHostingSubscriptionLifecycleService lifecycle; - private final TransactionTemplate transaction; - - public AccountHostingSubscriptionProvisioningService( - AccountHostingSubscriptionLifecycleRepository repository, - StripeHostingSubscriptionProvisioner provider, - AccountHostingSubscriptionLifecycleService lifecycle, - PlatformTransactionManager transactions) { - this.repository = Objects.requireNonNull(repository); - this.provider = Objects.requireNonNull(provider); - this.lifecycle = Objects.requireNonNull(lifecycle); - transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); - transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - } - - public Result provision(ProvisioningClaim claim, UUID dispatchId, UUID lifecycleRequestId) { - Objects.requireNonNull(claim, "Existing genuine owner provisioning claim is required"); - requireUuid(dispatchId); - requireUuid(lifecycleRequestId); - requireNoAmbientTransaction(); - ProviderDispatch dispatch; - try { - var prepared = - Objects.requireNonNull( - transaction.execute(status -> repository.prepareProviderDispatch(claim, dispatchId))); - dispatch = - Objects.requireNonNull( - transaction.execute(status -> repository.readProviderDispatch(prepared))); - } catch (FenceRejectedException refused) { - // Dispatch remains strictly fenced. A new local transaction may only settle the same retained - // work; stale/current-owner/reservation mismatches still reject there before any write. - Disposition disposition = - Objects.requireNonNull(transaction.execute(status -> repository.deferUnresolved(claim))); - return new Pending( - disposition, - new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); - } - requireNoAmbientTransaction(); - var located = provider.provision(dispatch); - if (!(located instanceof StripeHostingSubscriptionProvisioner.Located actual)) { - Disposition disposition = - Objects.requireNonNull( - transaction.execute(status -> repository.deferUnresolved(dispatch.claim()))); - return new Pending(disposition, located); - } - // Locator and actual observation select the existing owner operation, never an ad-hoc write. - TransitionResult transition = - lifecycle.reconcile( - lifecycleRequestId, - claim.creation().requestId(), - claim.subscriptionRowVersion(), - actual.providerSubscriptionId(), - claim.attemptId()); - if (transition.outcome() != Outcome.COMMITTED) { - return new Reconciling(transition); - } - AccountHostingSubscriptionCurrentReceipt current = - lifecycle.readCurrent(claim.creation().tenantId()); - if (!current.receiptRequestId().equals(lifecycleRequestId) - || current.current().rowVersion() != transition.committedRowVersion() - || !current.current().subscriptionId().equals(claim.creation().subscriptionId()) - || !current.current().creationRequestId().equals(claim.creation().requestId()) - || !actual.providerSubscriptionId().equals(current.current().providerSubscriptionId()) - || !current.current().planQuote().equals(claim.creation().planQuote())) { - throw new IllegalStateException("Independent committed hosting receipt readback mismatch"); - } - return new Committed(transition, current); - } - - private static void requireUuid(UUID value) { - if (value == null || value.equals(new UUID(0, 0))) { - throw new IllegalArgumentException("Non-nil hosting operation identity is required"); - } - } - - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("Hosting provisioner refuses an ambient SQL transaction"); - } - } - - public sealed interface Result permits Pending, Reconciling, Committed {} - - public record Pending( - Disposition disposition, StripeHostingSubscriptionProvisioner.Result providerResult) - implements Result {} - - public record Reconciling(TransitionResult transition) implements Result {} - - /** Privately constructed after actual lifecycle commit and independent current readback. */ - public static final class Committed implements Result { - private final TransitionResult transition; - private final AccountHostingSubscriptionCurrentReceipt current; - - private Committed( - TransitionResult transition, AccountHostingSubscriptionCurrentReceipt current) { - this.transition = transition; - this.current = current; - } - - public TransitionResult transition() { - return transition; - } - - public AccountHostingSubscriptionCurrentReceipt current() { - return current; - } - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 79c1169e9b..e40b79cd69 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -5,7 +5,6 @@ import static org.mockito.Mockito.mock; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -25,7 +24,6 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -283,188 +281,6 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE .isZero(); } - @Test - void receivingUpgradeFromParent1036Through1038PreservesCanonicalRowsAndHistory() { - String schema = createSchema("canonical_join_scope_"); - DriverManagerDataSource dataSource = postgres.dataSource(schema); - Flyway parent = accountFlyway(dataSource, schema, "1036"); - parent.migrate(); - parent.validate(); - assertThat(parent.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1036")); - - DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); - DSLContext transactionDsl = - DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - TransactionTemplate transaction = - new TransactionTemplate(new DataSourceTransactionManager(dataSource)); - Record account = - setupDsl.fetchOne( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " - + "RETURNING id, account_uuid", - "canonical-migration-upgrade-account", - "canonical-migration-upgrade@example.test", - "test-hash"); - long privateAccountId = Objects.requireNonNull(account).get("id", Long.class); - UUID accountUuid = Objects.requireNonNull(account).get("account_uuid", UUID.class); - - FreshTenantIdentityAssociationRepository freshTenants = - new FreshTenantIdentityAssociationRepository(transactionDsl, "prod"); - FreshTenantCreationEvidence tenantSource = freshTenantEvidence(); - transaction.executeWithoutResult(status -> freshTenants.importVerified(tenantSource)); - AccountConnectScopeRepository scopes = - new AccountConnectScopeRepository( - transactionDsl, mock(AccountTenantIdentityResolver.class), freshTenants); - AccountJoinOperationRepository operations = - new AccountJoinOperationRepository(transactionDsl, scopes); - CanonicalJoinScopeV2 scope = canonicalScope(accountUuid, tenantSource.canonicalTenantId()); - VerifiedTenantProvenance tenantProvenance = - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - tenantSource.operationId(), - tenantSource.evidenceDigest()); - String requestId = "canonical-migration-upgrade-pending"; - String callerBinding = "canonical-migration-upgrade-caller"; - transaction.executeWithoutResult( - status -> { - scopes.insertCanonical(privateAccountId, scope, tenantProvenance); - assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isTrue(); - }); - CanonicalJoinOperationEvidence pending = - transaction.execute( - status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow()); - assertThat(pending.status()).isEqualTo("PENDING"); - - String scopeTokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); - RetainedPhysicalRow retainedScope = - retainedPhysicalRow( - setupDsl, - "SELECT to_jsonb(scope_row)::text, scope_row.xmin::text " - + "FROM account_connect_scope_records scope_row WHERE scope_token_hash = ?", - scopeTokenHash); - RetainedPhysicalRow retainedIntent = - retainedPhysicalRow( - setupDsl, - "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " - + "FROM account_join_operations operation_row WHERE request_id = ?", - requestId); - List> parentHistory = flywayHistory(setupDsl); - assertThat(parentHistory) - .extracting(row -> row.get("script")) - .contains("V1036__hosting_subscription_terminal_resolution.sql") - .doesNotContain( - "V1037__canonical_join_failure_and_attempt_diagnostics.sql", - "V1038__canonical_join_existing_membership_terminal.sql"); - - Flyway current = accountFlyway(dataSource, schema, "1038"); - current.migrate(); - current.validate(); - assertThat(current.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1038")); - - List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 2); - assertThat(upgradedHistory.subList(0, parentHistory.size())) - .containsExactlyElementsOf(parentHistory); - List> addedHistory = - upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); - assertThat(addedHistory).extracting(row -> row.get("version")).containsExactly("1037", "1038"); - assertThat(addedHistory) - .extracting(row -> row.get("script")) - .containsExactly( - "V1037__canonical_join_failure_and_attempt_diagnostics.sql", - "V1038__canonical_join_existing_membership_terminal.sql"); - assertThat(addedHistory) - .allSatisfy( - row -> { - assertThat(row.get("checksum")).isNotNull(); - assertThat(row.get("success")).isEqualTo(true); - }); - assertThat( - retainedPhysicalRow( - setupDsl, - "SELECT to_jsonb(scope_row)::text, scope_row.xmin::text " - + "FROM account_connect_scope_records scope_row WHERE scope_token_hash = ?", - scopeTokenHash)) - .isEqualTo(retainedScope); - assertThat( - retainedPhysicalRow( - setupDsl, - "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " - + "FROM account_join_operations operation_row WHERE request_id = ?", - requestId)) - .isEqualTo(retainedIntent); - - List installedConstraints = - setupDsl - .fetch( - "SELECT constraint_row.conname FROM pg_constraint constraint_row " - + "JOIN pg_class table_row ON table_row.oid = constraint_row.conrelid " - + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " - + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " - + "AND constraint_row.contype = 'c' AND constraint_row.convalidated", - schema) - .getValues(0, String.class); - assertThat(installedConstraints) - .contains( - "account_join_v2_attempt_diagnostics_check", - "account_join_exact_first_transition_check", - "account_join_operation_representation_check", - "account_join_canonical_terminal_proof_check"); - assertThat( - Objects.requireNonNull( - setupDsl.fetchOne( - "SELECT count(*) FROM pg_trigger trigger_row " - + "JOIN pg_class table_row ON table_row.oid = trigger_row.tgrelid " - + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " - + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " - + "AND trigger_row.tgname = 'account_join_operation_identity_guard' " - + "AND trigger_row.tgenabled = 'O' AND NOT trigger_row.tgisinternal", - schema)) - .get(0, Long.class)) - .isEqualTo(1L); - String guardDefinition = - Objects.requireNonNull( - setupDsl.fetchOne( - "SELECT pg_get_functiondef(?::regprocedure)", - schema + ".guard_account_join_operation_identity()")) - .get(0, String.class); - assertThat(guardDefinition) - .contains("ALREADY_ACTIVE", "account_tenant_membership", "last_attempt_failure_code"); - - CanonicalJoinOperationEvidence diagnosed = - transaction.execute( - status -> - operations.recordCanonicalAttemptFailure( - requestId, scope, callerBinding, "NOT_EVALUATED", "AUTH_UNAVAILABLE")); - assertThat(diagnosed.status()).isEqualTo("PENDING"); - assertThat(diagnosed.lastAttemptAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); - assertThat(diagnosed.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); - RetainedPhysicalRow diagnosedIntent = - retainedPhysicalRow( - setupDsl, - "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " - + "FROM account_join_operations operation_row WHERE request_id = ?", - requestId); - assertThatThrownBy( - () -> - setupDsl.execute( - "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id = ?", - "changed-migration-caller", - requestId)) - .isInstanceOfSatisfying( - org.jooq.exception.DataAccessException.class, - failure -> assertThat(failure.sqlState()).isEqualTo("23514")); - assertThat( - retainedPhysicalRow( - setupDsl, - "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " - + "FROM account_join_operations operation_row WHERE request_id = ?", - requestId)) - .isEqualTo(diagnosedIntent); - } - @Test void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { String schema = createSchema("canonical_scope_cleanup_"); @@ -547,475 +363,6 @@ void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { assertThat(scopeRowCount(setupDsl, v2Scope.connectScopeId())).isEqualTo(1); } - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite( - boolean bound) { - JournalFixture f = journalFixture(); - if (bound) - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); - else - f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); - var original = f.read(); - String outcome = bound ? "IDEMPOTENCY_CONFLICT" : "CONNECT_SCOPE_INVALID"; - var failed = - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); - assertThat(failed.status()).isEqualTo("FAILED"); - assertThat(failed.outcome()).isEqualTo(outcome); - assertThat(failed.intentDigest()).isEqualTo(original.intentDigest()); - assertThat(failed.scopeEvidence()).isEqualTo(original.scopeEvidence()); - assertThat(failed.requestDigest()).isEqualTo(original.requestDigest()); - assertThat(failed.requestDigestVersion()).isEqualTo(original.requestDigestVersion()); - assertThat(failed.allowPublicJoin()).isEqualTo(original.allowPublicJoin()); - assertThat(failed.entitlementVersion()).isEqualTo(original.entitlementVersion()); - assertThat(failed.entitlementAuthorityAvailability()) - .isEqualTo(bound ? "AVAILABLE" : "NOT_EVALUATED"); - assertThat(failed.lastAttemptFailureCode()).isNull(); - assertThat(failed.membershipId()).isNull(); - assertThat(failed.terminalProof()).isNull(); - String retained = f.bytes(); - var replay = - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); - assertThat(replay).isEqualTo(failed); - assertThat(f.bytes()).isEqualTo(retained); - f.transaction() - .executeWithoutResult( - status -> - assertThat( - f.operations().insertCanonicalIntent(f.requestId(), f.scope(), f.caller())) - .isFalse()); - if (bound) { - var policyReplay = - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23)); - assertThat(policyReplay).isEqualTo(failed); - } else { - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23))) - .isInstanceOf( - AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - } - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), - f.scope(), - f.caller(), - "TENANT_BILLING_BLOCKED"))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), - f.scope(), - f.caller(), - "ENTITLEMENT_UNAVAILABLE"))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.dsl() - .execute( - "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE request_id = ?", - f.requestId())) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThat(f.bytes()).isEqualTo(retained); - f.assertNoSuccessEffects(); - } - - @Test - void - boundPendingUnavailableDiagnosticsNeverDowngradePolicyAndExactRecoveryOnlyClearsDiagnostics() { - JournalFixture f = journalFixture(); - var bound = - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23)); - var unavailable = - f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); - assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); - assertThat(unavailable.requestDigest()).isEqualTo(bound.requestDigest()); - assertThat(unavailable.entitlementVersion()).isEqualTo(23); - assertThat(unavailable.allowPublicJoin()).isTrue(); - assertThat(unavailable.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); - assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - var targetUnavailable = - f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalAttemptFailure( - f.requestId(), - f.scope(), - f.caller(), - "NOT_EVALUATED", - "AUTH_UNAVAILABLE")); - assertThat(targetUnavailable.requestDigest()).isEqualTo(bound.requestDigest()); - assertThat(targetUnavailable.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); - String beforeConflict = f.bytes(); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 24))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThat(f.bytes()).isEqualTo(beforeConflict); - var recovered = - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23)); - assertThat(recovered.requestDigest()).isEqualTo(bound.requestDigest()); - assertThat(recovered.entitlementVersion()).isEqualTo(bound.entitlementVersion()); - assertThat(recovered.allowPublicJoin()).isEqualTo(bound.allowPublicJoin()); - assertThat(recovered.lastAttemptAuthorityAvailability()).isEqualTo("AVAILABLE"); - assertThat(recovered.lastAttemptFailureCode()).isNull(); - String recoveredBytes = f.bytes(); - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); - assertThat(f.bytes()).isEqualTo(recoveredBytes); - f.assertNoSuccessEffects(); - } - - @Test - void definitivePublicJoinDenialRetainsItsAlreadyBoundNegativePolicy() { - JournalFixture f = journalFixture(); - var deniedPolicy = - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), false, 23)); - var failed = - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), - f.scope(), - f.caller(), - "PUBLIC_PRODUCTION_ADMISSION_DENIED")); - assertThat(failed.status()).isEqualTo("FAILED"); - assertThat(failed.allowPublicJoin()).isFalse(); - assertThat(failed.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); - assertThat(failed.requestDigest()).isEqualTo(deniedPolicy.requestDigest()); - assertThat(failed.entitlementVersion()).isEqualTo(deniedPolicy.entitlementVersion()); - f.assertNoSuccessEffects(); - } - - @Test - void failedJournalRejectsConflictingCallerRequestAndRetainedScopeWithoutRewritingReceipt() { - JournalFixture f = journalFixture(); - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); - String retained = f.bytes(); - var alternate = - canonicalScope("different-canonical-bearer", f.scope().accountId(), f.scope().tenantId()); - f.transaction() - .executeWithoutResult( - status -> - f.scopes() - .insertCanonical( - f.accountId(), alternate, f.read().scopeEvidence().tenantProvenance())); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), - f.scope(), - "different-caller", - "CONNECT_SCOPE_INVALID"))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - "different-global-request", - f.scope(), - f.caller(), - "CONNECT_SCOPE_INVALID"))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), alternate, f.caller(), "CONNECT_SCOPE_INVALID"))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThat(f.bytes()).isEqualTo(retained); - } - - @Test - void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerminalMutation() { - JournalFixture f = journalFixture(); - String original = f.bytes(); - for (String change : - java.util.List.of( - "status = 'FAILED', outcome = 'ENTITLEMENT_UNAVAILABLE'", - "status = 'FAILED', outcome = 'CONNECT_SCOPE_INVALID', membership_id = 1", - "status = 'COMMITTED', outcome = 'JOINED'", - "intent_digest = 'sha256:" + "b".repeat(64) + "'")) { - assertThatThrownBy( - () -> - f.dsl() - .execute( - "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", - f.requestId())) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThat(f.bytes()).isEqualTo(original); - } - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); - String bound = f.bytes(); - for (String change : - java.util.List.of( - "entitlement_authority_availability = 'UNAVAILABLE'", - "entitlement_version = 24", - "request_digest = NULL", - "last_attempt_authority_availability = 'UNAVAILABLE', last_attempt_failure_code = NULL")) { - assertThatThrownBy( - () -> - f.dsl() - .execute( - "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", - f.requestId())) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThat(f.bytes()).isEqualTo(bound); - } - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); - String terminal = f.bytes(); - assertThatThrownBy( - () -> - f.dsl() - .execute( - "DELETE FROM account_join_operations WHERE request_id = ?", f.requestId())) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy(() -> f.dsl().execute("TRUNCATE account_join_operations")) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThat(f.bytes()).isEqualTo(terminal); - f.assertNoSuccessEffects(); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction(boolean bound) { - JournalFixture f = journalFixture(); - if (bound) - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); - String original = f.bytes(); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> { - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE"); - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID"); - throw new IllegalStateException("controlled canonical journal rollback"); - })) - .hasMessageContaining("controlled canonical journal rollback"); - assertThat(f.bytes()).isEqualTo(original); - var failed = - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); - assertThat(failed.status()).isEqualTo("FAILED"); - f.assertNoSuccessEffects(); - } - - private JournalFixture journalFixture() { - String schema = createSchema("canonical_join_scope_"); - var source = postgres.dataSource(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); - DSLContext setup = DSL.using(source, SQLDialect.POSTGRES); - DSLContext owner = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); - var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); - var account = - Objects.requireNonNull( - setup.fetchOne( - "INSERT INTO accounts (username, email, password_hash) VALUES ('journal-player', 'journal@example.test', 'controlled-hash') RETURNING id, account_uuid")); - long privateAccountId = account.get("id", Long.class); - UUID accountId = account.get("account_uuid", UUID.class); - var fresh = new FreshTenantIdentityAssociationRepository(owner, "prod"); - var tenant = freshTenantEvidence(); - transaction.executeWithoutResult(status -> fresh.importVerified(tenant)); - var scopes = - new AccountConnectScopeRepository(owner, mock(AccountTenantIdentityResolver.class), fresh); - var operations = new AccountJoinOperationRepository(owner, scopes); - var scope = canonicalScope(accountId, tenant.canonicalTenantId()); - String requestId = "journal-" + UUID.randomUUID(); - String caller = "controlled-journal-caller"; - transaction.executeWithoutResult( - status -> { - scopes.insertCanonical( - privateAccountId, - scope, - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - tenant.operationId(), - tenant.evidenceDigest())); - operations.insertCanonicalIntent(requestId, scope, caller); - }); - return new JournalFixture( - setup, transaction, operations, scopes, scope, privateAccountId, requestId, caller); - } - - /** Physical journal storage proof only; supplied caller/scope selectors do not authenticate. */ - private record JournalFixture( - DSLContext dsl, - TransactionTemplate transaction, - AccountJoinOperationRepository operations, - AccountConnectScopeRepository scopes, - CanonicalJoinScopeV2 scope, - long accountId, - String requestId, - String caller) { - private CanonicalJoinOperationEvidence read() { - return Objects.requireNonNull( - transaction.execute( - status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow())); - } - - private String bytes() { - return Objects.requireNonNull( - dsl.fetchOne( - "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", - requestId)) - .get(0, String.class); - } - - private void assertNoSuccessEffects() { - for (String table : - java.util.List.of( - "account_tenant_membership", - "account_authority_outbox_events", - "account_audit_outbox")) assertThat(dsl.fetchCount(DSL.table(table))).isZero(); - assertThat(read().membershipId()).isNull(); - assertThat(read().terminalProof()).isNull(); - } - } - - private static Flyway accountFlyway( - DriverManagerDataSource dataSource, String schema, String targetVersion) { - var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration", "classpath:db/migration/saga"); - if (targetVersion != null) { - configuration.target(MigrationVersion.fromVersion(targetVersion)); - } - return configuration.load(); - } - - private static List> flywayHistory(DSLContext dsl) { - return dsl.fetch( - "SELECT installed_rank, version, description, type, script, checksum, installed_by, " - + "installed_on, execution_time, success FROM flyway_schema_history " - + "ORDER BY installed_rank") - .intoMaps(); - } - - private static RetainedPhysicalRow retainedPhysicalRow( - DSLContext dsl, String query, Object... bindings) { - Record row = Objects.requireNonNull(dsl.fetchOne(query, bindings)); - return new RetainedPhysicalRow(row.get(0, String.class), row.get(1, String.class)); - } - - private record RetainedPhysicalRow(String rowJson, String xmin) {} - private static long scopeRowCount(DSLContext dsl, String connectScopeId) { return Objects.requireNonNull( dsl.fetchOne( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java deleted file mode 100644 index d1fcb8ae4e..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ /dev/null @@ -1,1222 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.stripe.exception.StripeException; -import com.stripe.model.StripeObject; -import com.stripe.net.ApiMode; -import com.stripe.net.ApiResource.RequestMethod; -import com.stripe.net.BaseAddress; -import com.stripe.net.RequestOptions; -import com.stripe.net.StripeResponseGetter; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; -import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; -import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; -import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionProvisioningService; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import tools.jackson.databind.json.JsonMapper; - -/** Actual owner/SDK composition with controlled enrollment publications and provider transport. */ -@Testcontainers(disabledWithoutDocker = true) -class AccountHostingSubscriptionDispatchPostgresIntegrationTest { - private static final String DIGEST = "sha256:" + "a".repeat(64); - private static final AtomicLong GAME_ROWS = new AtomicLong(90000); - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void upgradeRetainsPriorAttemptOneAndAddsOnlyNonAuthorizingUnknownGuard() { - Fixture f = fixture("1030"); - ProvisioningClaim claim = claim(f, 1); - var before = new java.util.LinkedHashMap>>(); - for (String table : - List.of( - "accounts", - "subscription_create_operations", - "subscription", - "subscription_provisioning_work", - "subscription_provisioning_attempts")) { - before.put( - table, - f.dsl() - .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") - .intoMaps()); - } - migrate(f.source(), f.schema(), "1032"); - for (var entry : before.entrySet()) { - assertThat( - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " - + entry.getKey() - + " t") - .intoMaps()) - .isEqualTo(entry.getValue()); - } - assertThat( - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT classification FROM subscription_provider_dispatch_claim")) - .get(0, String.class)) - .isEqualTo("PREEXISTING_UNKNOWN"); - var prepared = f.tx().execute(s -> f.owner().prepareProviderDispatch(claim, UUID.randomUUID())); - var read = f.tx().execute(s -> f.owner().readProviderDispatch(prepared)); - assertThat(read.readyForProviderIo()).isTrue(); - assertThat(read.initialCallAllowed()).isFalse(); - } - - @Test - void upgradeRetainsControlledUnclaimedWorkWithoutInventingDispatchHistory() { - Fixture f = fixture("1030"); - // Controlled retained state is inserted directly with the normal SQL guards enabled. The - // existing production claim owner does not commit nonterminal work without its first attempt. - f.tx() - .executeWithoutResult( - s -> - f.dsl() - .execute( - "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " - + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " - + "SELECT request_id, subscription_id, 'RECONCILING', 1, 0, 4, 3, 10000, 1000, " - + "created_at + interval '1 hour', created_at FROM subscription_create_operations WHERE request_id = ?", - f.creation().requestId())); - var retained = - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM subscription_provisioning_work t") - .intoMaps(); - assertThat(retained).hasSize(1); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); - - migrate(f.source(), f.schema(), "1032"); - - assertThat( - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM subscription_provisioning_work t") - .intoMaps()) - .isEqualTo(retained); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); - var first = claim(f, 1); - assertThat(first.attemptNumber()).isOne(); - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(f.transport().creates).isOne(); - assertThat( - Objects.requireNonNull( - f.dsl().fetchOne("SELECT * FROM subscription_provider_dispatch_claim")) - .intoMap()) - .containsEntry("classification", "FIRST_DISPATCH") - .containsEntry("first_attempt_id", first.attemptId()) - .containsEntry("first_claimed_row_version", first.subscriptionRowVersion()); - } - - @Test - void upgradeRetainsExpiredFirstClaimAsTerminalWithoutInventingDispatchHistory() { - Fixture f = fixture("1030"); - f.clock().advance(Duration.ofHours(1)); - var failed = - f.tx().execute(s -> f.owner().claim(f.creation().requestId(), 1, UUID.randomUUID())); - assertThat(failed.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat(failed.claim()).isNull(); - assertThat( - Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) - .intoMap()) - .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") - .containsEntry("attempt_count", 0) - .containsEntry("failure_reason", "ABSOLUTE_DEADLINE"); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); - var retained = new java.util.LinkedHashMap>>(); - for (String table : - List.of( - "subscription", - "subscription_provisioning_work", - "subscription_provisioning_operator_outbox", - "subscription_instrument_reservations")) { - retained.put( - table, - f.dsl() - .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") - .intoMaps()); - } - - migrate(f.source(), f.schema(), "1032"); - - var replay = - f.tx().execute(s -> f.owner().claim(f.creation().requestId(), 1, UUID.randomUUID())); - assertThat(replay.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat(replay.claim()).isNull(); - for (var entry : retained.entrySet()) { - assertThat( - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " - + entry.getKey() - + " t") - .intoMaps()) - .isEqualTo(entry.getValue()); - } - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); - assertThat(f.transport().creates).isZero(); - assertThat(f.transport().searches).isZero(); - } - - @Test - void onlyOneFreshInsertionCarriesInitialPermissionAndIndependentReadbackIsMandatory() - throws Exception { - Fixture f = fixture("1032"); - ProvisioningClaim claim = claim(f, 1); - var start = new CountDownLatch(1); - try (var executor = Executors.newFixedThreadPool(2)) { - var first = - executor.submit( - () -> { - start.await(); - return prepareAndRead(f, claim); - }); - var second = - executor.submit( - () -> { - start.await(); - return prepareAndRead(f, claim); - }); - start.countDown(); - var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); - assertThat(results) - .extracting(ProviderDispatch::initialCallAllowed) - .containsExactlyInAnyOrder(true, false); - assertThat(prepareAndRead(f, claim).initialCallAllowed()).isFalse(); - } - assertThat(ProviderDispatch.class.getConstructors()).isEmpty(); - } - - @Test - void uncommittedSameTransactionReadbackCannotProduceProviderPermission() { - Fixture f = fixture("1032"); - var claim = claim(f, 1); - assertThatThrownBy( - () -> - f.tx() - .execute( - s -> { - var uncommitted = - f.owner().prepareProviderDispatch(claim, UUID.randomUUID()); - return f.owner().readProviderDispatch(uncommitted); - })) - .hasMessageContaining("new transaction"); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); - } - - @Test - void expiredExactAttemptReturnsTypedPendingAndReplacedStaleWorkerHitsBindingFence() { - Fixture f = fixture("1032"); - var original = claim(f, 1); - prepareAndRead(f, original); - f.clock().advance(Duration.ofSeconds(11)); - var before = new java.util.LinkedHashMap>>(); - for (String table : - List.of( - "subscription", - "subscription_provisioning_work", - "subscription_provisioning_attempts", - "subscription_instrument_reservations", - "subscription_provider_dispatch_claim")) { - before.put( - table, - f.dsl() - .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") - .intoMaps()); - } - Disposition expired = f.tx().execute(status -> f.owner().deferUnresolved(original)); - assertThat(expired).isEqualTo(Disposition.ATTEMPT_EXPIRED); - for (var entry : before.entrySet()) { - assertThat( - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " - + entry.getKey() - + " t") - .intoMaps()) - .isEqualTo(entry.getValue()); - } - var replacement = claim(f, original.subscriptionRowVersion()); - assertThat(replacement.attemptId()).isNotEqualTo(original.attemptId()); - before.replaceAll( - (table, rows) -> - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") - .intoMaps()); - // Replacement advanced the subscription version, so the original binding rejects this stale - // worker before the later attempt-identity check can run. - assertThatThrownBy(() -> f.tx().execute(status -> f.owner().deferUnresolved(original))) - .isExactlyInstanceOf(FenceRejectedException.class) - .hasMessage("Pending claim owner/customer/instrument/subscription fence rejected"); - for (var entry : before.entrySet()) { - assertThat( - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " - + entry.getKey() - + " t") - .intoMaps()) - .isEqualTo(entry.getValue()); - } - assertThat(f.transport().creates).isZero(); - } - - @Test - void recoveredUndispatchedAttemptMayOwnFirstDispatchButReplayAndExpiredReadbackCannot() { - Fixture f = fixture("1032"); - var first = claim(f, 1); - // Simulate a crash after the worker claim commits but before any dispatch transaction. - f.clock().advance(Duration.ofSeconds(11)); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); - assertThat(f.transport().creates).isZero(); - var second = claim(f, first.subscriptionRowVersion()); - assertThat(second.attemptNumber()).isEqualTo(2); - var prepared = - f.tx().execute(s -> f.owner().prepareProviderDispatch(second, UUID.randomUUID())); - assertThat(f.tx().execute(s -> f.owner().readProviderDispatch(prepared)).initialCallAllowed()) - .isTrue(); - assertThat(prepareAndRead(f, second).initialCallAllowed()).isFalse(); - f.clock().advance(Duration.ofSeconds(10)); - assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) - .isInstanceOf(FenceRejectedException.class) - .hasMessage("Exact live provisioning claim readback rejected"); - } - - @Test - void expiredUndispatchedFirstClaimRecoversThroughExactlyOneInitialCreate() { - Fixture f = fixture("1032"); - var first = claim(f, 1); - f.clock().advance(Duration.ofSeconds(11)); - var second = claim(f, first.subscriptionRowVersion()); - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(result.current().current().subscriptionId()) - .isEqualTo(f.creation().subscriptionId()); - assertThat(f.transport().creates).isEqualTo(1); - var dispatch = - Objects.requireNonNull( - f.dsl().fetchOne("SELECT * FROM subscription_provider_dispatch_claim")); - assertThat(dispatch.get("classification", String.class)).isEqualTo("FIRST_DISPATCH"); - assertThat(dispatch.get("first_attempt_id", UUID.class)).isEqualTo(second.attemptId()); - assertThat(dispatch.get("first_claimed_row_version", Long.class)) - .isEqualTo(second.subscriptionRowVersion()); - } - - @Test - void dispatchIdentityBindingClassificationAndTimeCannotChangeOrDisappear() { - Fixture f = fixture("1032"); - prepareAndRead(f, claim(f, 1)); - var before = f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps(); - for (String command : - List.of( - "UPDATE subscription_provider_dispatch_claim SET classification='PREEXISTING_UNKNOWN'", - "UPDATE subscription_provider_dispatch_claim SET recorded_at=recorded_at+interval '1 second'", - "UPDATE subscription_provider_dispatch_claim SET dispatch_id='" - + UUID.randomUUID() - + "'", - "DELETE FROM subscription_provider_dispatch_claim", - "TRUNCATE subscription_provider_dispatch_claim")) { - assertThatThrownBy(() -> f.dsl().execute(command)) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - } - assertThat(f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps()) - .isEqualTo(before); - } - - @Test - void realInitialSdkCreateFlowsThroughExistingLifecycleCommitAndIndependentCurrentRead() { - Fixture f = fixture("1032"); - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(claim(f, 1), UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(result.current().current().subscriptionId()) - .isEqualTo(f.creation().subscriptionId()); - assertThat(f.transport().creates).isEqualTo(1); - assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(3); - } - - @Test - void liveFinalBudgetDispatchSurvivesDisplayRefreshAndCompetingClaim() { - Fixture f = fixture("1032"); - var first = claim(f, 1); - f.clock().advance(Duration.ofSeconds(11)); - var second = claim(f, first.subscriptionRowVersion()); - f.clock().advance(Duration.ofSeconds(11)); - var finalClaim = claim(f, second.subscriptionRowVersion()); - assertThat(finalClaim.attemptNumber()).isEqualTo(3); - f.transport().duringCreate = - () -> { - refreshDisplay(f); - var competing = - f.tx() - .execute( - s -> - f.owner() - .claim( - f.creation().requestId(), - finalClaim.subscriptionRowVersion(), - UUID.randomUUID())); - assertThat(competing.disposition()).isEqualTo(Disposition.WAITING); - assertThat(competing.claim()).isNull(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) - .isZero(); - }; - - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(finalClaim, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(f.transport().creates).isOne(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isEqualTo(3); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isOne(); - } - - @Test - void lostCreateResponseRecoversAfterTransientEmptySearchWithoutRecreating() { - Fixture f = fixture("1032"); - f.transport().loseCreateResponse = true; - var first = claim(f, 1); - var lost = - (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); - assertThat(lost.disposition()).isEqualTo(Disposition.WAITING); - assertThat(((StripeHostingSubscriptionProvisioner.Pending) lost.providerResult()).reason()) - .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); - assertThat(f.transport().creates).isEqualTo(1); - f.transport().emptySearchesRemaining = 1; - f.clock().advance(Duration.ofSeconds(2)); - var second = claim(f, first.subscriptionRowVersion()); - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(f.transport().creates).isEqualTo(1); - assertThat(f.transport().searches).isEqualTo(2); - assertThat(f.transport().lists).isEqualTo(1); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isOne(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); - } - - @Test - void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservation() { - Fixture f = fixture("1032"); - f.transport().loseCreateResponse = true; - var first = claim(f, 1); - var lost = - (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); - assertThat(lost.disposition()).isEqualTo(Disposition.WAITING); - assertThat(((StripeHostingSubscriptionProvisioner.Pending) lost.providerResult()).reason()) - .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); - assertThat(f.transport().exists).isTrue(); - f.transport().emptySearchesRemaining = 2; - f.transport().emptyListsRemaining = 2; - ProvisioningClaim previous = first; - for (int attempt = 2; attempt <= 3; attempt++) { - f.clock().advance(Duration.ofSeconds(2)); - previous = claim(f, previous.subscriptionRowVersion()); - var pending = - (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(previous, UUID.randomUUID(), UUID.randomUUID()); - assertThat(pending.disposition()) - .isEqualTo(attempt == 3 ? Disposition.TERMINAL_FAILURE : Disposition.WAITING); - assertThat(pending.providerResult()) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); - assertThat(f.transport().creates).isEqualTo(1); - } - long finalVersion = previous.subscriptionRowVersion(); - var retry = - Objects.requireNonNull( - f.tx() - .execute( - s -> - f.owner() - .claim(f.creation().requestId(), finalVersion, UUID.randomUUID()))); - assertThat(retry.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat(retry.claim()).isNull(); - assertThat(f.transport().searches).isEqualTo(3); - assertThat(f.transport().lists).isEqualTo(2); - assertThat(f.transport().creates).isEqualTo(1); - var current = - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT status, provider_subscription_id, terminal_resolution_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId())); - assertThat(current.get("status", String.class)).isEqualTo("provisioning"); - assertThat(current.get("provider_subscription_id")).isNull(); - assertThat(current.get("terminal_resolution_id")).isNull(); - assertThat( - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId())) - .get("released_at")) - .isNull(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_terminal_resolutions"))) - .isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); - assertThat( - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT phase, failure_reason FROM subscription_provisioning_work WHERE request_id = ?", - f.creation().requestId())) - .intoMap()) - .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") - .containsEntry("failure_reason", "STALLED_WITHOUT_COMMITTED_PROGRESS"); - } - - @Test - void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline() { - Fixture f = fixture("1032"); - var original = claim(f, 1); - var originalRows = f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps(); - var reservation = - f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps(); - refreshDisplay(f); - - assertThatThrownBy( - () -> - f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID()))) - .isInstanceOf(FenceRejectedException.class); - var refused = - (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(original, UUID.randomUUID(), UUID.randomUUID()); - assertThat(refused.disposition()).isEqualTo(Disposition.WAITING); - assertThat(refused.providerResult()) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); - var waiting = - f.tx() - .execute( - s -> - f.owner() - .claim( - f.creation().requestId(), - original.subscriptionRowVersion(), - UUID.randomUUID())); - assertThat(waiting.disposition()).isEqualTo(Disposition.WAITING); - assertThat(waiting.claim()).isNull(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isOne(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); - f.clock().advance(Duration.ofHours(1)); - - var terminal = - f.tx() - .execute( - s -> - f.owner() - .claim( - f.creation().requestId(), - original.subscriptionRowVersion(), - UUID.randomUUID())); - assertThat(terminal.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat(terminal.claim()).isNull(); - assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) - .isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat( - Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) - .intoMap()) - .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") - .containsEntry("failure_reason", "ABSOLUTE_DEADLINE"); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); - assertThat(f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps()) - .usingRecursiveComparison() - .isEqualTo(originalRows); - assertThat(f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps()) - .isEqualTo(reservation); - assertThat(Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription")).intoMap()) - .containsEntry("status", "provisioning") - .containsEntry("provider_subscription_id", null) - .containsEntry("terminal_resolution_id", null); - assertThat(f.transport().creates).isZero(); - assertThat(f.transport().searches).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_terminal_resolutions"))) - .isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); - } - - @Test - void displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDeadlineFailure() { - Fixture f = fixture("1032"); - var original = claim(f, 1); - var prepared = - f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID())); - var dispatchRows = - f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps(); - refreshDisplay(f); - - assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) - .isInstanceOf(FenceRejectedException.class); - assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) - .isEqualTo(Disposition.WAITING); - f.clock().advance(Duration.ofHours(1)); - assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) - .isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat(f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps()) - .isEqualTo(dispatchRows); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); - assertThat(f.transport().creates).isZero(); - } - - @Test - void displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch() { - Fixture unclaimed = fixture(null); - refreshDisplay(unclaimed); - var refused = - unclaimed - .tx() - .execute( - s -> - unclaimed - .owner() - .claim(unclaimed.creation().requestId(), 1, UUID.randomUUID())); - assertThat(Objects.requireNonNull(refused).disposition()) - .isEqualTo(Disposition.TERMINAL_FAILURE); - assertThat(refused.claim()).isNull(); - assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_work"))).isOne(); - assertThat( - Objects.requireNonNull( - unclaimed.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) - .intoMap()) - .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") - .containsEntry("failure_reason", "RESERVED_INSTRUMENT_CHANGED"); - assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) - .isOne(); - assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))) - .isZero(); - assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) - .isZero(); - assertThat(unclaimed.transport().creates).isZero(); - assertThat(unclaimed.transport().searches).isZero(); - } - - @Test - void displayRefreshDoesNotAuthorizeDirectDispatchInsert() { - Fixture retained = fixture("1032"); - var original = claim(retained, 1); - refreshDisplay(retained); - // Exercise the unchanged V1032 insertion guard independently of the Java eligibility fence. - assertThatThrownBy( - () -> - retained - .tx() - .execute( - s -> - retained - .dsl() - .execute( - "INSERT INTO subscription_provider_dispatch_claim " - + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " - + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " - + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", - retained.creation().requestId(), - retained.creation().subscriptionId(), - retained.creation().subscriptionProvisioningRequestId(), - UUID.randomUUID(), - original.attemptId(), - original.subscriptionRowVersion(), - retained.clock().instant().atOffset(ZoneOffset.UTC)))) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence"); - assertThat(retained.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) - .isZero(); - assertThat(retained.transport().creates).isZero(); - } - - @Test - void displayRefreshDoesNotLetStaleWorkerSettleReplacementOrRewriteOriginalBinding() { - Fixture f = fixture("1032"); - var first = claim(f, 1); - f.clock().advance(Duration.ofSeconds(11)); - var replacement = claim(f, first.subscriptionRowVersion()); - refreshDisplay(f); - var before = f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps(); - assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(first))) - .isInstanceOf(FenceRejectedException.class); - assertThatThrownBy( - () -> - f.tx() - .execute(s -> f.owner().claim(f.creation().requestId(), 1, first.attemptId()))) - .isInstanceOf(FenceRejectedException.class); - assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) - .isEqualTo(before); - // Private claims are not caller-constructible. A controlled changed-creation double still must - // not substitute for the immutable retained original during the local settlement readback. - var changedCreation = mock(AccountSubscriptionCreationRecord.class); - when(changedCreation.requestId()).thenReturn(f.creation().requestId()); - var changedClaim = mock(ProvisioningClaim.class); - when(changedClaim.creation()).thenReturn(changedCreation); - when(changedClaim.attemptId()).thenReturn(replacement.attemptId()); - when(changedClaim.subscriptionRowVersion()).thenReturn(replacement.subscriptionRowVersion()); - assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(changedClaim))) - .isInstanceOf(FenceRejectedException.class) - .hasMessage("Exact retained provisioning settlement claim rejected"); - // The database also retains its existing owner-change guard; this component cannot invent an - // unaudited transfer merely to manufacture a changed-current-owner state. - assertThatThrownBy( - () -> - f.tx() - .execute( - s -> - f.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, " - + "owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - f.creation().tenantId()))) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) - .isEqualTo(before); - assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); - assertThat(f.transport().creates).isZero(); - } - - private static void refreshDisplay(Fixture f) { - var instruments = new AccountPaymentInstrumentRepository(f.dsl()); - var original = f.creation(); - var instrument = - instruments - .findByOwner(original.owner().accountUuid(), original.paymentInstrumentId()) - .orElseThrow(); - in( - f.tx(), - () -> - instruments.recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - instrument.instrumentUuid(), - instrument.accountUuid(), - instrument.rowVersion(), - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new AccountPaymentInstrumentRecord.DisplayMetadata("visa", "4242", 12, 2031), - DIGEST))); - } - - private static ProviderDispatch prepareAndRead(Fixture f, ProvisioningClaim claim) { - var prepared = f.tx().execute(s -> f.owner().prepareProviderDispatch(claim, UUID.randomUUID())); - assertThat(prepared.readyForProviderIo()).isFalse(); - assertThat(prepared.initialCallAllowed()).isFalse(); - return f.tx().execute(s -> f.owner().readProviderDispatch(prepared)); - } - - private static ProvisioningClaim claim(Fixture f, long version) { - return Objects.requireNonNull( - f.tx() - .execute( - s -> - f.owner().claim(f.creation().requestId(), version, UUID.randomUUID()).claim())); - } - - private static AccountHostingSubscriptionProvisioningService service(Fixture f) { - var stripe = new com.stripe.StripeClient(f.transport()); - var lifecycle = - new AccountHostingSubscriptionLifecycleService( - f.owner(), - new StripeHostingSubscriptionObserver( - stripe, f.clock(), Duration.ofMillis(250), Duration.ofSeconds(1)), - new DataSourceTransactionManager(f.source())); - return new AccountHostingSubscriptionProvisioningService( - f.owner(), - new StripeHostingSubscriptionProvisioner( - stripe, f.clock(), false, Duration.ofMillis(250), Duration.ofSeconds(1)), - lifecycle, - new DataSourceTransactionManager(f.source())); - } - - private static Fixture fixture(String target) { - String schema = "hosting_dispatch_" + UUID.randomUUID().toString().replace("-", ""); - var source = - new DriverManagerDataSource( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - source.setSchema(schema); - migrate(source, schema, target); - DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); - var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); - transaction.setTimeout(10); - var catalog = - new AccountHostingPlanCatalog( - List.of( - new AccountHostingPlanCatalog.ConfiguredPlan( - "hosting", "price_controlled", "1", "100", "2", "1048576"))); - var intents = new AccountSubscriptionIntentRepository(dsl, catalog); - long row = GAME_ROWS.incrementAndGet(); - UUID accountUuid = enroll(dsl, transaction, row); - UUID tenantId = UUID.randomUUID(); - UUID tenantCreateRequest = UUID.randomUUID(); - UUID tenantCreateOperation = UUID.randomUUID(); - String tenantKey = "hosting-fixture-game-" + row; - String tenantRequestDigest = - GameTenantCreationDigest.requestDigest( - "prod", tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); - var tenantSource = - new FreshTenantCreationEvidence( - 1, - "prod", - tenantCreateRequest, - tenantCreateOperation, - tenantRequestDigest, - tenantId, - row, - tenantKey, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - "prod", - tenantCreateRequest, - tenantCreateOperation, - tenantRequestDigest, - tenantId, - row, - tenantKey, - "NEW_GAME_ROW")); - in( - transaction, - () -> { - new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenantSource); - return new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantId); - }); - - UUID authorizationOperation = UUID.randomUUID(); - var creator = - new FreshTenantCreatorEvidence( - 1, - tenantSource, - accountUuid, - authorizationOperation, - DIGEST, - FreshTenantCreatorDigest.evidenceDigest( - 1, tenantSource, accountUuid, authorizationOperation, DIGEST)); - var owner = - in( - transaction, - () -> - new AccountInitialTenantBillingOwnerRepository(dsl) - .establishInitial( - new AccountInitialTenantBillingOwnerRepository.InitialRequest( - UUID.randomUUID(), creator, UUID.randomUUID(), 1, true))); - - var customers = new AccountBillingCustomerRepository(dsl); - var pendingCustomer = - in( - transaction, - () -> - customers - .retainIntent(accountUuid, UUID.randomUUID(), UUID.randomUUID()) - .customer()); - var customer = - in( - transaction, - () -> - customers.recordObservation( - accountUuid, - pendingCustomer.customerProvisioningRequestId(), - 1, - UUID.randomUUID(), - AccountBillingCustomerRecord.Observation.CONFIRMED, - "cus_" + row, - DIGEST)); - var instrument = - in( - transaction, - () -> - new AccountPaymentInstrumentRepository(dsl) - .retainAttachment( - new AccountPaymentInstrumentRepository.Attachment( - UUID.randomUUID(), - UUID.randomUUID(), - accountUuid, - customer.customerProvisioningRequestId(), - customer.providerCustomerId(), - "pm_" + row, - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new AccountPaymentInstrumentRecord.DisplayMetadata( - "visa", "4242", 12, 2030), - DIGEST))); - var creation = - in( - transaction, - () -> - intents.retainPending( - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - tenantId, - new OwnerFence(accountUuid, owner.ownerVersion(), owner.ownerGeneration()), - "hosting", - instrument.instrumentUuid(), - 1, - new ProducerEvidence(accountUuid, UUID.randomUUID(), DIGEST), - null))); - - var clock = new MutableClock(creation.createdAt().plusSeconds(1)); - var lifecycleOwner = - new AccountHostingSubscriptionLifecycleRepository( - dsl, - intents, - clock, - new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( - 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), - new AccountHostingSubscriptionLifecyclePolicy( - Duration.ofSeconds(15), - new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( - Duration.ofSeconds(60), Duration.ofSeconds(120))), - "prod", - false); - var transport = new Transport(creation, instrument.providerPaymentMethodId(), clock); - return new Fixture( - source, schema, dsl, transaction, creation, lifecycleOwner, clock, transport); - } - - private static UUID enroll(DSLContext dsl, TransactionTemplate tx, long suffix) { - return in( - tx, - () -> { - // Controlled publications stipulate delivery; the actual fresh insertion/certification - // owners - // run normally. These fixtures do not qualify production publisher or protected-mount - // custody. - for (Category category : Category.values()) { - UUID publication = UUID.randomUUID(), - policy = UUID.randomUUID(), - closure = UUID.randomUUID(); - String identity = AccountFreshEnrollmentPolicySource.sourceIdentity(category); - byte[] bytes; - try { - bytes = - Rfc8785CanonicalJson.canonicalizeUtf8( - JsonMapper.builder() - .build() - .writeValueAsString( - Map.of( - "schemaVersion", - "account-fresh-enrollment-policy/v1", - "category", - category.storageValue(), - "sourceIdentity", - identity, - "publicationId", - publication.toString(), - "revision", - "1", - "policyId", - policy.toString(), - "policyRule", - "CERTIFY_NEW_ACTIVE_ACCOUNT", - "closureId", - closure.toString(), - "closureRule", - "EXACT_FRESH_INSERT_ONLY"))); - } catch (java.io.IOException failure) { - throw new IllegalStateException(failure); - } - dsl.execute( - "INSERT INTO account_fresh_enrollment_policy_publications " - + "(publication_id, category, revision, policy_id, closure_id, policy_rule, closure_rule, source_identity, source_root, publication_digest, publication_bytes) " - + "VALUES (?, ?, 1, ?, ?, 'CERTIFY_NEW_ACTIVE_ACCOUNT', 'EXACT_FRESH_INSERT_ONLY', ?, ?, ?, ?)", - publication, - category.storageValue(), - policy, - closure, - identity, - "/controlled-test/owner-protected-mount", - AccountFreshEnrollmentPolicySource.digest(bytes), - bytes); - dsl.execute( - "INSERT INTO account_fresh_enrollment_policy_current (category, publication_id, revision) VALUES (?, ?, 1)", - category.storageValue(), - publication); - } - var generations = new AccountAuthorityGenerationRepository(dsl); - var outbox = new AccountAuthorityOutboxRepository(dsl); - var restrictions = - new AccountPlatformRestrictionOperationRepository( - dsl, - generations, - outbox, - new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox), - new AccountPlatformRestrictionBirthRepository(dsl)); - var result = - new AccountFreshEnrollmentRepository( - dsl, - new AccountRepository(dsl), - new AccountFreshEnrollmentPolicyRepository(dsl), - restrictions) - .enroll( - new AccountFreshEnrollmentRequest( - UUID.randomUUID(), - "hosting-" + suffix, - "hosting-" + suffix + "@example.test", - "controlled-password-verifier", - true, - "PASSWORD,EMAIL_OTP")); - return result.accountUuid(); - }); - } - - private static T in(TransactionTemplate tx, java.util.function.Supplier action) { - return Objects.requireNonNull(tx.execute(s -> action.get())); - } - - private static void migrate(DriverManagerDataSource source, String schema, String target) { - var configuration = - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration", "classpath:db/migration/saga"); - if (target != null) { - configuration.target(target); - } - configuration.load().migrate(); - } - - private record Fixture( - DriverManagerDataSource source, - String schema, - DSLContext dsl, - TransactionTemplate tx, - AccountSubscriptionCreationRecord creation, - AccountHostingSubscriptionLifecycleRepository owner, - MutableClock clock, - Transport transport) {} - - private static final class MutableClock extends Clock { - private Instant now; - - private MutableClock(Instant now) { - this.now = now; - } - - private void advance(Duration duration) { - now = now.plus(duration); - } - - @Override - public ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return now; - } - } - - private static final class Transport implements StripeResponseGetter { - private final AccountSubscriptionCreationRecord creation; - private final String paymentMethod; - private final Clock clock; - private boolean exists; - private boolean loseCreateResponse; - private Runnable duringCreate; - private int emptySearchesRemaining; - private int emptyListsRemaining; - private int searches; - private int lists; - private int creates; - private int subscriptionReads; - - private Transport( - AccountSubscriptionCreationRecord creation, String paymentMethod, Clock clock) { - this.creation = creation; - this.paymentMethod = paymentMethod; - this.clock = clock; - } - - @Override - @SuppressWarnings("unchecked") - public T request( - BaseAddress base, - RequestMethod method, - String path, - Map params, - Type type, - RequestOptions options, - ApiMode mode) - throws StripeException { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - String response; - if (path.equals("/v1/customers/" + creation.providerCustomerId())) { - response = - "{\"object\":\"customer\",\"id\":\"" - + creation.providerCustomerId() - + "\",\"livemode\":false,\"deleted\":false,\"metadata\":{\"firemud_metadata_schema_version\":\"1\"," - + "\"firemud_operation_type\":\"customer_provisioning\",\"firemud_operation_id\":\"" - + creation.customerProvisioningRequestId() - + "\",\"firemud_account_id\":\"" - + creation.owner().accountUuid() - + "\"}}"; - } else if (path.equals("/v1/payment_methods/" + paymentMethod)) { - response = - "{\"object\":\"payment_method\",\"id\":\"" - + paymentMethod - + "\",\"customer\":\"" - + creation.providerCustomerId() - + "\",\"livemode\":false,\"type\":\"card\",\"card\":{\"brand\":\"visa\",\"last4\":\"4242\",\"exp_month\":12,\"exp_year\":2030}}"; - } else if (path.equals("/v1/subscriptions/search")) { - searches++; - assertThat(params.get("query").toString()) - .contains( - creation.subscriptionProvisioningRequestId().toString(), - creation.subscriptionId().toString()); - boolean visible = exists && emptySearchesRemaining == 0; - if (emptySearchesRemaining > 0) { - emptySearchesRemaining--; - } - response = - "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" - + (visible ? subscription() : "") - + "]}"; - } else if ("/v1/subscriptions".equals(path) && method == RequestMethod.GET) { - lists++; - assertThat(params) - .containsEntry("customer", creation.providerCustomerId()) - .containsEntry("status", "all"); - boolean visible = exists && emptyListsRemaining == 0; - if (emptyListsRemaining > 0) { - emptyListsRemaining--; - } - response = - "{\"object\":\"list\",\"has_more\":false,\"data\":[" - + (visible ? subscription() : "") - + "]}"; - } else if (path.equals("/v1/subscriptions") && method == RequestMethod.POST) { - creates++; - exists = true; - assertThat(options.getIdempotencyKey()) - .isEqualTo(creation.subscriptionProvisioningRequestId().toString()); - assertThat(params) - .containsEntry("customer", creation.providerCustomerId()) - .containsEntry("default_payment_method", paymentMethod); - assertThat(params.get("items")) - .isEqualTo( - List.of( - Map.of( - "price", - creation.planQuote().providerPriceId(), - "quantity", - creation.planQuote().providerQuantity()))); - if (duringCreate != null) { - Runnable action = duringCreate; - duringCreate = null; - action.run(); - } - if (loseCreateResponse) { - throw org.mockito.Mockito.mock(StripeException.class); - } - response = subscription(); - } else if (path.equals("/v1/subscriptions/sub_exact")) { - subscriptionReads++; - response = subscription(); - } else { - throw new AssertionError("Unexpected provider path " + path); - } - return (T) com.stripe.net.ApiResource.GSON.fromJson(response, type); - } - - private String subscription() { - return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"" - + creation.providerCustomerId() - + "\",\"default_payment_method\":\"" - + paymentMethod - + "\",\"livemode\":false,\"status\":\"active\",\"cancel_at_period_end\":false," - + "\"metadata\":{\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"subscription_provisioning\"," - + "\"firemud_operation_id\":\"" - + creation.subscriptionProvisioningRequestId() - + "\",\"firemud_subscription_id\":\"" - + creation.subscriptionId() - + "\"}," - + "\"items\":{\"has_more\":false,\"data\":[{\"id\":\"si_exact\",\"object\":\"subscription_item\",\"subscription\":\"sub_exact\"," - + "\"quantity\":" - + creation.planQuote().providerQuantity() - + ",\"current_period_start\":" - + clock.instant().minusSeconds(5).getEpochSecond() - + ",\"current_period_end\":" - + clock.instant().plusSeconds(3600).getEpochSecond() - + ",\"price\":{\"id\":\"" - + creation.planQuote().providerPriceId() - + "\",\"object\":\"price\"}}]}}"; - } - - @Override - public InputStream requestStream( - BaseAddress base, - RequestMethod method, - String path, - Map params, - RequestOptions options, - ApiMode mode) { - throw new AssertionError("No streaming"); - } - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java deleted file mode 100644 index da0f3691b3..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java +++ /dev/null @@ -1,1989 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; - -import com.stripe.exception.StripeException; -import com.stripe.model.StripeObject; -import com.stripe.net.ApiMode; -import com.stripe.net.ApiResource.RequestMethod; -import com.stripe.net.BaseAddress; -import com.stripe.net.RequestOptions; -import com.stripe.net.StripeResponseGetter; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.sql.SQLException; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.AuthorizedActor; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; -import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.configuration.FluentConfiguration; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Actual PostgreSQL + actual Stripe SDK over CONTROLLED read-only transport. Creator/consent and - * customer/wallet enrollment are controlled source inputs, not qualification of their live issuers. - * No trigger is disabled, no confirmed SDK value is fabricated, and no remote Stripe call is made. - */ -@Testcontainers(disabledWithoutDocker = true) -class AccountHostingSubscriptionLifecyclePostgresIntegrationTest { - private static final String DIGEST = "sha256:" + "a".repeat(64); - private static final AtomicLong ROWS = new AtomicLong(10_000); - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void actualSdkReadCommitsExactMappingReceiptCanonicalStreamsAndConsistentReaderThenReplays() { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); - var committed = - f.service() - .reconcile( - request, - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()); - assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); - assertThat(committed.committedRowVersion()).isEqualTo(4); - var current = f.service().readCurrent(f.creation().tenantId()); - assertThat(current.subscriptionStatus()).isEqualTo(Status.ACTIVE); - assertThat(current.gameplayAvailable()).isTrue(); - assertThat(current.allowPublicJoin()).isTrue(); - assertThat(current.current().planQuote()).isEqualTo(f.creation().planQuote()); - assertThat(current.current().providerSubscriptionId()).isEqualTo(f.providerId()); - assertThat(current.entitlementVersion()).isOne(); - assertThat(current.tenantBillingSequence()).isOne(); - assertThat(current.tenantAuthorityEvent().tenantBillingSequence()) - .isEqualTo(current.tenantBillingSequence()); - assertThat(current.tenantAuthorityEvent().tenantBillingEventDigest()) - .isEqualTo(current.billingEventDigest()); - var source = - one( - c, - "SELECT * FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", - f.creation().tenantId()); - assertThat(source.get("last_request_id", UUID.class)).isEqualTo(request); - assertThat(source.get("current_generation", Long.class)).isEqualTo(2); - assertThat( - one( - c, - "SELECT o.recorded_transaction_id = r.committed_transaction_id AS same_transaction " - + "FROM subscription_lifecycle_observations o JOIN subscription_lifecycle_receipts r USING (attempt_id) WHERE r.request_id = ?", - request) - .get("same_transaction", Boolean.class)) - .isTrue(); - assertThat( - one( - c, - "SELECT phase FROM subscription_provisioning_work WHERE request_id = ?", - f.creation().requestId()) - .get("phase", String.class)) - .isEqualTo("CONFIRMED"); - assertThat(count(c, "subscription_provider_history")).isOne(); - assertThat(count(c, "account_demo_tenant_entitlements")).isZero(); - int reads = f.transport().reads; - assertThat( - f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())) - .isEqualTo(committed); - assertThat(f.transport().reads).isEqualTo(reads); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); - assertThatThrownBy( - () -> - f.service() - .reconcile( - request, f.creation().requestId(), 2, "sub_other", claim.attemptId())) - .hasMessageContaining("IDEMPOTENCY_CONFLICT"); - assertThat(f.transport().reads).isEqualTo(reads); - } - - @Test - void trialUsesRetainedQuoteWithoutTodaysCatalogAndSqlShapedRowsAloneNeverAuthorize() { - Context c = context("1030"); - Fixture f = fixture(c); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThat(f.transport().reads).isZero(); - f.transport().json = response(f, "trialing"); - var emptyCatalogRepository = - new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); - var owner = owner(c, f.clock(), emptyCatalogRepository); - var service = service(c, owner, f.transport(), f.clock()); - var claim = service.claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); - assertThat( - service - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - 2, - f.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - assertThat(service.readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.TRIALING); - assertThat(service.readCurrent(f.creation().tenantId()).current().planQuote()) - .isEqualTo(f.creation().planQuote()); - assertSqlState( - "23514", - () -> c.setup().execute("UPDATE subscription_lifecycle_receipts SET status = 'active'")); - assertSqlState( - "23514", - () -> - c.setup().execute("UPDATE subscription_lifecycle_observations SET payload = payload")); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET plan_quote_digest = ?, row_version = row_version + 1 WHERE subscription_id = ?", - "sha256:" + "f".repeat(64), - f.creation().subscriptionId())); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE billing_customer SET provider_customer_id = 'cus_wrong', row_version = row_version + 1 WHERE account_uuid = ?", - f.creation().owner().accountUuid())); - } - - @Test - void rawSqlActiveMappingWithoutGenuineClaimAndReceiptCannotBecomeAReadOrLifecycleSource() { - Context c = context("1030"); - Fixture f = fixture(c); - c.tx() - .executeWithoutResult( - s -> { - c.dsl() - .execute( - "INSERT INTO subscription_provider_history (provider_subscription_id, subscription_id, operation_kind, request_id, " - + "provider_operation_id, role, effective_at, evidence_digest) VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", - f.providerId(), - f.creation().subscriptionId(), - f.creation().requestId(), - f.creation().subscriptionProvisioningRequestId(), - f.clock().instant().atOffset(ZoneOffset.UTC), - DIGEST); - c.dsl() - .execute( - "UPDATE subscription SET status = 'active', provider_subscription_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", - f.providerId(), - f.creation().subscriptionId()); - }); - assertThat(c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().status()) - .isEqualTo("active"); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThatThrownBy( - () -> - f.service() - .reconcile( - UUID.randomUUID(), f.creation().requestId(), 2, f.providerId(), null)) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - assertThat(f.transport().reads).isZero(); - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThat(count(c, "account_tenant_authority_source_records")).isZero(); - } - - @Test - void hostingExtendsExistingDemoStreamsWithoutRewritingOrReinterpretingDemoEvidence() { - Context c = context("1030"); - Fixture f = fixture(c); - var identity = new FreshTenantIdentityAssociationRepository(c.dsl(), "prod"); - var generations = new AccountAuthorityGenerationRepository(c.dsl()); - var billing = new AccountTenantEntitlementOutboxRepository(c.dsl()); - var events = - new AccountTenantAuthorityEventRepository( - c.dsl(), new AccountAuthorityOutboxRepository(c.dsl()), billing, identity, generations); - var demo = - new AccountDemoTenantEntitlementRepository(c.dsl(), identity, generations, billing, events); - var source = in(c, () -> identity.read(f.creation().tenantId()).orElseThrow()); - var demoRequest = - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - source.canonicalTenantId(), - source.creationRequestId(), - source.requestDigest(), - null, - null, - null, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(5, 1, 1024)); - in(c, () -> demo.provision(demoRequest, source)); - var demoRow = - one( - c, - "SELECT row_to_json(e)::text AS value, xmin::text AS xmin FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", - source.canonicalTenantId()); - byte[] demoEvent = - one( - c, - "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 1", - source.canonicalTenantId()) - .get("payload", byte[].class); - activate(f); - var current = f.service().readCurrent(source.canonicalTenantId()); - assertThat(current.entitlementVersion()).isEqualTo(2); - assertThat(current.tenantBillingSequence()).isEqualTo(2); - assertThat(current.tenantAuthorityEvent().tenantAuthorityGeneration()).isEqualTo(3); - assertThat(current.subscriptionStatus()).isEqualTo(Status.ACTIVE); - assertThat( - one( - c, - "SELECT row_to_json(e)::text AS value, xmin::text AS xmin FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", - source.canonicalTenantId())) - .isEqualTo(demoRow); - assertThat( - one( - c, - "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 1", - source.canonicalTenantId()) - .get("payload", byte[].class)) - .isEqualTo(demoEvent); - assertThat(count(c, "account_tenant_entitlement_outbox_streams")).isOne(); - assertThat(count(c, "account_authority_outbox_streams")).isOne(); - assertThat(count(c, "account_tenant_authority_source_records")).isOne(); - } - - @Test - void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransition() - throws Exception { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); - CountDownLatch reading = new CountDownLatch(1); - CountDownLatch completeRead = new CountDownLatch(1); - f.transport().duringRead = - () -> { - reading.countDown(); - await(completeRead); - }; - var executor = Executors.newSingleThreadExecutor(); - try { - var winner = - executor.submit( - () -> - f.service() - .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); - assertThat(reading.await(5, TimeUnit.SECONDS)).isTrue(); - assertThat( - f.service() - .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.RECONCILING); - completeRead.countDown(); - var committed = winner.get(10, TimeUnit.SECONDS); - assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); - assertThat( - f.service() - .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())) - .isEqualTo(committed); - assertThat(f.transport().reads).isOne(); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "subscription_provider_history")).isOne(); - } finally { - completeRead.countDown(); - executor.shutdownNow(); - } - } - - @Test - void providerIdMetadataCustomerInstrumentPriceQuantityAndUnknownStatusesCannotBecomeAuthority() { - Context c = context("1030"); - for (String mismatch : - List.of("id", "metadata", "customer", "instrument", "price", "quantity", "unknown")) { - Fixture f = fixture(c); - var claim = claim(f); - String json = response(f, "active"); - f.transport().json = - switch (mismatch) { - case "id" -> json.replace(f.providerId(), "sub_wrong"); - case "metadata" -> - json.replace( - f.creation().subscriptionProvisioningRequestId().toString(), - UUID.randomUUID().toString()); - case "customer" -> json.replace(f.creation().providerCustomerId(), "cus_wrong"); - case "instrument" -> json.replace(f.instrument().providerPaymentMethodId(), "pm_wrong"); - case "price" -> json.replace(f.creation().planQuote().providerPriceId(), "price_wrong"); - case "quantity" -> json.replace("\"quantity\":1", "\"quantity\":2"); - default -> json.replace("\"active\"", "\"unrecognized_status\""); - }; - UUID request = UUID.randomUUID(); - assertThat( - f.service() - .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .as(mismatch) - .isEqualTo(Outcome.RECONCILING); - assertThat( - one( - c, - "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", - request) - .get("state", String.class)) - .isEqualTo("PENDING"); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThat( - one( - c, - "SELECT provider_subscription_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId()) - .get("provider_subscription_id")) - .isNull(); - } - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThat(count(c, "subscription_provider_history")).isZero(); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isZero(); - } - - @Test - void providerExceptionIsNotAbsenceAndSameRequestRecoversWithoutAnotherProviderIdentity() { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); - f.transport().failure = mock(StripeException.class); - assertThat( - f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.RECONCILING); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); - assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNull(); - f.transport().failure = null; - f.clock().advance(Duration.ofSeconds(2)); - assertThat( - f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - assertThat(count(c, "subscription_create_operations")).isOne(); - assertThat(count(c, "subscription_create_provider_identities")).isEqualTo(2); - assertThat(count(c, "subscription_lifecycle_attempts")).isEqualTo(2); - assertThat(f.service().readCurrent(f.creation().tenantId()).allowPublicJoin()).isTrue(); - } - - @Test - void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsRejectBeforeRead() { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - assertThatThrownBy( - () -> - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - 1, - f.providerId(), - claim.attemptId())) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - assertThat(f.transport().reads).isZero(); - var wrongOwner = - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - f.creation().tenantId(), - new OwnerFence( - f.creation().owner().accountUuid(), - f.creation().owner().version() + 1, - UUID.randomUUID()), - f.creation().planCode(), - f.creation().paymentInstrumentId(), - f.creation().reservedInstrumentVersion(), - new ProducerEvidence(f.creation().owner().accountUuid(), UUID.randomUUID(), DIGEST), - null); - assertThatThrownBy(() -> c.tx().execute(s -> c.intents().retainPending(wrongOwner))) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - f.transport().duringRead = - () -> - in( - c, - () -> - new AccountPaymentInstrumentRepository(c.dsl()) - .recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - f.instrument().instrumentUuid(), - f.creation().owner().accountUuid(), - 1L, - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new AccountPaymentInstrumentRecord.DisplayMetadata( - "visa", "4242", 12, 2031), - DIGEST))); - assertThat( - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - 2, - f.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - assertThat( - new AccountPaymentInstrumentRepository(c.dsl()) - .findByOwner(f.creation().owner().accountUuid(), f.instrument().instrumentUuid()) - .orElseThrow() - .rowVersion()) - .isEqualTo(2L); - assertThat( - c.intents() - .findCurrentByTenant(f.creation().tenantId()) - .orElseThrow() - .reservedInstrumentVersion()) - .isEqualTo(1L); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_tenant_authority_source_records")).isOne(); - assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.ACTIVE); - } - - @Test - void - deferredSqlFailureRollsBackMappingObservationReceiptGenerationAndBothEventsThenRetryRecovers() { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); - var prepared = - in( - c, - () -> - f.owner() - .prepare( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); - var actualSdk = f.observer().observe(prepared.binding()); - assertSqlState( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> { - assertThat(f.owner().apply(prepared, actualSdk).outcome()) - .isEqualTo(Outcome.COMMITTED); - var sameTransactionFence = - f.owner().prepareCurrentRead(f.creation().tenantId()); - assertThat( - f.owner() - .readCurrent(sameTransactionFence, actualSdk) - .allowPublicJoin()) - .isTrue(); - // A real monotonic generation advance without its source event must fail at - // transaction - // completion, after the lifecycle owner's ordinary writes and exact readback - // have executed. - c.dsl() - .execute( - "UPDATE account_authority_generations SET generation = generation + 1, source_version = source_version + 1 " - + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", - f.creation().tenantId()); - })); - for (String table : - List.of( - "subscription_provider_history", - "subscription_lifecycle_observations", - "subscription_lifecycle_receipts", - "account_tenant_entitlement_outbox_events", - "account_authority_outbox_events", - "account_tenant_authority_source_records")) { - assertThat(count(c, table)).as(table).isZero(); - } - assertThat( - one( - c, - "SELECT generation FROM account_authority_generations WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", - f.creation().tenantId()) - .get("generation", Long.class)) - .isOne(); - assertThat( - one( - c, - "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", - request) - .get("state", String.class)) - .isEqualTo("PENDING"); - f.clock().advance(Duration.ofSeconds(12)); - assertThat( - f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()).isOne(); - } - - @Test - void databaseGuardRejectsUnauditedOwnerUpdateDuringSdkTransport() { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - // The actual database refuses an unaudited transfer. Preserve that guard rather than - // manufacturing an owner change that this source boundary cannot legitimately produce. - f.transport().duringRead = - () -> - c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - f.creation().tenantId())); - UUID reconciliationRequest = UUID.randomUUID(); - assertSqlState( - "23514", - () -> - f.service() - .reconcile( - reconciliationRequest, - f.creation().requestId(), - 2, - f.providerId(), - claim.attemptId())); - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThat(count(c, "subscription_provider_history")).isZero(); - assertThat(count(c, "account_authority_outbox_events")).isZero(); - assertThat( - one( - c, - "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", - reconciliationRequest) - .get("state", String.class)) - .isEqualTo("PENDING"); - assertThat( - one( - c, - "SELECT lifecycle_inflight_request_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId()) - .get("lifecycle_inflight_request_id", UUID.class)) - .isEqualTo(reconciliationRequest); - assertThat( - one( - c, - "SELECT current_receipt_request_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId()) - .get("current_receipt_request_id", UUID.class)) - .isNull(); - assertThat( - one( - c, - "SELECT owner_version FROM account_tenant_billing_owners WHERE tenant_uuid = ?", - f.creation().tenantId()) - .get("owner_version", Long.class)) - .isEqualTo(f.creation().owner().version()); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - } - - @Test - void realInitialCanceledEvidenceRetiresOnlyItsHoldAndCommittedReceiptCannotBeDetached() { - Context c = context("1030"); - Fixture f = fixture(c); - f.transport().json = response(f, "canceled"); - var claim = claim(f); - assertThat( - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - 2, - f.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); - assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNotNull(); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET current_receipt_request_id = NULL, row_version = row_version + 1 WHERE subscription_id = ?", - f.creation().subscriptionId())); - assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.CANCELED); - } - - @Test - void freshReadsBeyondObservationAgePreserveCommittedReceiptAndAuthorityUntilRealPeriodEnd() { - for (String status : List.of("active", "trialing")) { - Context c = context("1030"); - Fixture f = fixture(c); - f.transport().json = response(f, status); - activate(f); - var receipt = - one( - c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r"); - var authority = - one( - c, - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); - Instant periodEnd = Instant.ofEpochSecond(f.creation().createdAt().getEpochSecond() + 3600); - assertThat( - one(c, "SELECT valid_until FROM subscription_lifecycle_receipts") - .get(0, java.time.OffsetDateTime.class) - .toInstant()) - .isEqualTo(periodEnd); - int reads = f.transport().reads; - for (int laterRead = 1; laterRead <= 2; laterRead++) { - f.clock().advance(Duration.ofSeconds(30)); - var current = f.service().readCurrent(f.creation().tenantId()); - assertThat(current.gameplayAvailable()).isTrue(); - assertThat(current.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); - assertThat(current.tenantBillingSequence()).isOne(); - assertThat(current.tenantAuthorityEvent().tenantAuthorityGeneration()).isEqualTo(2); - assertThat(f.transport().reads).isEqualTo(reads + laterRead); - assertThat( - one( - c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r")) - .isEqualTo(receipt); - assertThat( - one( - c, - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) - .isEqualTo(authority); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); - } - f.clock().advance(Duration.between(f.clock().instant(), periodEnd)); - int beforeExpiredRead = f.transport().reads; - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .isInstanceOf( - AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE") - .cause() - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) - .hasMessageContaining("current receipt is expired"); - assertThat(f.transport().reads).isEqualTo(beforeExpiredRead); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - } - } - - @Test - void canceledReceiptsReturnFreshNegativeProjectionAfterOriginalObservationAgeWithoutMutation() { - for (boolean providerCanceled : new boolean[] {true, false}) { - Context c = context("1030"); - Fixture f = fixture(c); - f.transport().json = - providerCanceled - ? response(f, "canceled") - : response(f, "active") - .replace( - "\"cancel_at\":null", - "\"cancel_at\":" + f.clock().instant().getEpochSecond()); - String originalFacts = f.transport().json; - activate(f); - var receipt = - one( - c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r"); - var authority = - one( - c, - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); - for (int laterRead = 0; laterRead < 2; laterRead++) { - f.clock().advance(Duration.ofSeconds(30)); - var canceled = f.service().readCurrent(f.creation().tenantId()); - assertThat(canceled.subscriptionStatus()).isEqualTo(Status.CANCELED); - assertThat(canceled.gameplayAvailable()).isFalse(); - assertThat(canceled.allowPublicJoin()).isFalse(); - assertThat(canceled.allowNewGameplayBindings()).isFalse(); - assertThat(canceled.allowNewInstanceStarts()).isFalse(); - assertThat(canceled.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); - assertThat(canceled.tenantBillingSequence()).isOne(); - } - // An aged terminal receipt is not permission to turn unknown or changed facts into denial. - f.transport().duringRead = () -> f.clock().advance(Duration.ofSeconds(15)); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .isInstanceOf( - AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); - f.transport().json = response(f, "active"); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .isInstanceOf( - AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); - f.transport().json = originalFacts; - assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); - assertThat( - one( - c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r")) - .isEqualTo(receipt); - assertThat( - one( - c, - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) - .isEqualTo(authority); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "subscription_provider_terminal_resolutions")) - .isEqualTo(providerCanceled ? 1 : 0); - } - } - - @Test - void inFlightAndStaleObservationOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot() { - Context c = context("1030"); - Fixture f = fixture(c); - activate(f); - var fence = in(c, () -> f.owner().prepareCurrentRead(f.creation().tenantId())); - f.transport().json = response(f, "past_due"); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - f.transport().json = response(f, "active"); - f.clock().advance(Duration.ofSeconds(15)); - assertThat(f.service().readCurrent(f.creation().tenantId()).allowPublicJoin()).isTrue(); - f.transport().duringRead = () -> f.clock().advance(Duration.ofSeconds(15)); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThat(f.service().readCurrent(f.creation().tenantId()).allowPublicJoin()).isTrue(); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); - long currentVersion = - c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); - var prepared = - in( - c, - () -> - f.owner() - .prepare( - UUID.randomUUID(), - f.creation().requestId(), - currentVersion, - f.providerId(), - null)); - var actualSdk = f.observer().observe(prepared.binding()); - assertThatThrownBy(() -> in(c, () -> f.owner().readCurrent(fence, actualSdk))) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - in(c, () -> f.owner().apply(prepared, actualSdk)); - assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()) - .isEqualTo(2); - } - - @Test - void unchangedInvalidEvidenceExhaustsFrozenStallBudgetOnceAndNeverReleasesBillingWork() { - Context c = context("1030"); - Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); - f.transport().json = response(f, "active").replace("price_controlled", "price_wrong"); - for (int attempt = 1; attempt <= 3; attempt++) { - var outcome = - f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome(); - assertThat(outcome).isEqualTo(attempt == 3 ? Outcome.TERMINAL_FAILURE : Outcome.RECONCILING); - f.clock().advance(Duration.ofSeconds(2)); - } - int reads = f.transport().reads; - assertThat( - f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.TERMINAL_FAILURE); - assertThat(f.transport().reads).isEqualTo(reads); - assertThat(count(c, "subscription_lifecycle_operator_outbox")).isOne(); - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); - assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNull(); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - } - - @Test - void firstPastDueObservationWithoutRetainedRecoveryOriginStaysUnresolvedAndHoldsReservation() { - Context c = context("1030"); - Fixture f = fixture(c); - activate(f); - var receipt = - one( - c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin, past_due_since FROM subscription_lifecycle_receipts r"); - assertThat(receipt.get("past_due_since")).isNull(); - var authority = - one( - c, - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); - var generations = - c.setup() - .fetch( - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_authority_generations a") - .intoMaps(); - long version = - c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); - UUID request = UUID.randomUUID(); - f.transport().json = response(f, "past_due"); - var unresolved = - f.service().reconcile(request, f.creation().requestId(), version, f.providerId(), null); - assertThat(unresolved.requestId()).isEqualTo(request); - assertThat(unresolved.outcome()).isEqualTo(Outcome.RECONCILING); - assertThat(unresolved.reason()).isEqualTo("RECOVERY_ORIGIN_UNRESOLVED"); - assertThat(unresolved.committedRowVersion()).isZero(); - var pending = - one( - c, - "SELECT state, failure_reason FROM subscription_lifecycle_operations WHERE request_id = ?", - request); - assertThat(pending.get("state", String.class)).isEqualTo("PENDING"); - assertThat(pending.get("failure_reason", String.class)).isEqualTo("RECOVERY_ORIGIN_UNRESOLVED"); - var observation = - one( - c, - "SELECT raw_status, mapping_reason FROM subscription_lifecycle_observations WHERE request_id = ?", - request); - assertThat(observation.get("raw_status", String.class)).isEqualTo("past_due"); - assertThat(observation.get("mapping_reason", String.class)) - .isEqualTo("RECOVERY_ORIGIN_UNRESOLVED"); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .isInstanceOf( - AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); - assertThat( - one( - c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin, past_due_since FROM subscription_lifecycle_receipts r")) - .isEqualTo(receipt); - assertThat( - one( - c, - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) - .isEqualTo(authority); - assertThat( - c.setup() - .fetch( - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_authority_generations a") - .intoMaps()) - .isEqualTo(generations); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); - assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNull(); - } - - @Test - void effectiveCancellationAdvancesMonotonicCutoffWithoutPrematureReservationRelease() { - Context c = context("1030"); - Fixture f = fixture(c); - activate(f); - Instant cancellation = - Instant.ofEpochSecond(f.clock().instant().plusSeconds(2).getEpochSecond()); - f.transport().json = - response(f, "active") - .replace("\"cancel_at\":null", "\"cancel_at\":" + cancellation.getEpochSecond()); - refresh(f); - f.clock().advance(Duration.between(f.clock().instant(), cancellation)); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - refresh(f); - var canceled = f.service().readCurrent(f.creation().tenantId()); - assertThat(canceled.subscriptionStatus()).isEqualTo(Status.CANCELED); - assertThat(canceled.allowPublicJoin()).isFalse(); - assertThat(canceled.gameplayAvailable()).isFalse(); - assertThat(canceled.allowNewGameplayBindings()).isFalse(); - assertThat(canceled.allowNewInstanceStarts()).isFalse(); - assertThat(canceled.cutoffAt()).isEqualTo(cancellation); - assertThat(canceled.tenantBillingSequence()).isEqualTo(3); - assertThat( - new String( - one( - c, - "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 3", - f.creation().tenantId()) - .get("payload", byte[].class), - java.nio.charset.StandardCharsets.UTF_8)) - .contains("TenantBillingStateChanged"); - f.clock().advance(Duration.ofSeconds(30)); - var laterCanceled = f.service().readCurrent(f.creation().tenantId()); - assertThat(laterCanceled.subscriptionStatus()).isEqualTo(Status.CANCELED); - assertThat(laterCanceled.cutoffAt()).isEqualTo(cancellation); - assertThat(laterCanceled.gameplayAvailable()).isFalse(); - assertThat(laterCanceled.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); - assertThat(laterCanceled.tenantBillingSequence()).isEqualTo(3); - assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(3); - assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNull(); - // Effective hosting cutoff is not proof that the provider can no longer charge. Neither the - // typed replacement owner nor structural SQL may strand that still-held original operation. - assertThatThrownBy( - () -> - in( - c, - () -> - c.intents() - .retainPending( - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - f.creation().tenantId(), - f.creation().owner(), - f.creation().planCode(), - f.instrument().instrumentUuid(), - 1, - new ProducerEvidence( - f.creation().owner().accountUuid(), - UUID.randomUUID(), - DIGEST), - new AccountSubscriptionCreateRequest.ReplacementFence( - f.creation().subscriptionId(), - canceled.current().rowVersion()))))) - .isInstanceOf(AccountSubscriptionIntentRepository.ConflictException.class); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET superseded_at = clock_timestamp(), " - + "superseded_by_request_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", - UUID.randomUUID(), - f.creation().subscriptionId())); - assertThat(count(c, "subscription_create_operations")).isOne(); - f.transport().json = - response(f, "canceled") - .replace("\"ended_at\":null", "\"ended_at\":" + cancellation.getEpochSecond()); - refresh(f); - assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()) - .isEqualTo(4); - assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNotNull(); - assertThat(c.intents().lookupProviderId(f.providerId()).disposition()) - .isEqualTo(AccountSubscriptionIntentRepository.MappingDisposition.TERMINAL_HISTORY); - assertThat( - one( - c, - "SELECT row_version FROM payment_instrument WHERE instrument_uuid = ?", - f.instrument().instrumentUuid()) - .get("row_version", Long.class)) - .isOne(); - var beforeReplacement = c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow(); - in( - c, - () -> - c.intents() - .retainPending( - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - f.creation().tenantId(), - f.creation().owner(), - f.creation().planCode(), - f.instrument().instrumentUuid(), - 1, - new ProducerEvidence( - f.creation().owner().accountUuid(), UUID.randomUUID(), DIGEST), - new AccountSubscriptionCreateRequest.ReplacementFence( - f.creation().subscriptionId(), beforeReplacement.rowVersion())))); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(4); - assertThat(count(c, "subscription_provider_history")).isOne(); - } - - @Test - void populatedV1029UpgradePreservesIntentQuoteRowAndFlywayHistoryWithoutSynthesizingReceipts() { - Context c = context("1029"); - Fixture f = fixture(c); - var before = - one( - c, - "SELECT row_to_json(s)::text AS value, xmin::text AS xmin FROM subscription s WHERE subscription_id = ?", - f.creation().subscriptionId()); - var intent = - one( - c, - "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM subscription_create_operations o WHERE request_id = ?", - f.creation().requestId()); - var history = - c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); - configuration(c).target("1030").load().migrate(); - var after = - one( - c, - "SELECT (to_jsonb(s) - 'lifecycle_inflight_request_id' - 'current_receipt_request_id')::text AS value, xmin::text AS xmin " - + "FROM subscription s WHERE subscription_id = ?", - f.creation().subscriptionId()); - // jsonb comparison avoids treating key order as row mutation. - assertThat( - one( - c, - "SELECT ?::jsonb = ?::jsonb AS same", - before.get("value", String.class), - after.get("value", String.class)) - .get("same", Boolean.class)) - .isTrue(); - assertThat(after.get("xmin", String.class)).isEqualTo(before.get("xmin", String.class)); - assertThat( - one( - c, - "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM subscription_create_operations o WHERE request_id = ?", - f.creation().requestId())) - .isEqualTo(intent); - var afterHistory = - c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); - assertThat(afterHistory).hasSize(history.size() + 1); - assertThat(afterHistory.subList(0, history.size())).isEqualTo(history); - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - } - - private static AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim claim(Fixture f) { - return Objects.requireNonNull( - f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim()); - } - - @Test - void committedTerminalCancellationReplaysAfterCanceledSubscriptionIsReplaced() { - FailedResolution f = failedResolution(); - Context c = f.fixture.context(); - var owner = f.fixture.owner(); - var prepared = in(c, () -> owner.prepareTerminalResolution(f.request)); - f.fixture.transport().json = response(f.fixture, "canceled"); - var sdk = f.fixture.observer().observe(prepared.binding()); - var committed = - in(c, () -> owner.applyTerminalResolution(prepared, sdk, target -> authorized(f))); - var predecessor = c.intents().findCurrentByTenant(f.request.tenantId()).orElseThrow(); - var successor = - in( - c, - () -> - c.intents() - .retainPending( - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - f.request.tenantId(), - f.fixture.creation().owner(), - f.fixture.creation().planCode(), - f.fixture.instrument().instrumentUuid(), - 1, - new ProducerEvidence( - f.request.actorAccountId(), UUID.randomUUID(), DIGEST), - new AccountSubscriptionCreateRequest.ReplacementFence( - f.request.subscriptionId(), predecessor.rowVersion())))); - List retained = resolutionImage(c); - var replay = in(c, () -> owner.prepareTerminalResolution(f.request)); - assertThat(replay.replayResult()).isEqualTo(committed); - assertThat( - in( - c, - () -> - owner.applyTerminalResolution( - replay, - null, - target -> { - assertThat(target.currentSubscriptionVersion()) - .isEqualTo(committed.committedRowVersion()); - return authorized(f); - }))) - .isEqualTo(committed); - assertThat(resolutionImage(c)).isEqualTo(retained); - assertThat(c.intents().findCurrentByTenant(f.request.tenantId()).orElseThrow().subscriptionId()) - .isEqualTo(successor.subscriptionId()); - assertThatThrownBy( - () -> - in( - c, - () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) - .hasMessageContaining("IDEMPOTENCY_CONFLICT"); - assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); - } - - @Test - void - terminalCancellationResolutionCommitsOneCanonicalReceiptAndReplaysWithoutChangingFailureHistory() { - FailedResolution f = failedResolution(); - Context c = f.fixture.context(); - var owner = f.fixture.owner(); - List before = resolutionImage(c); - var prepared = in(c, () -> owner.prepareTerminalResolution(f.request)); - assertThat(resolutionImage(c)).isEqualTo(before); - f.fixture.transport().json = response(f.fixture, "canceled"); - var sdk = f.fixture.observer().observe(prepared.binding()); - AtomicInteger callbacks = new AtomicInteger(); - var result = - in( - c, - () -> - owner.applyTerminalResolution( - prepared, - sdk, - target -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat(target.billingOwnerAccountId()) - .isEqualTo( - c.intents() - .findCreation(f.request.creationRequestId()) - .orElseThrow() - .owner() - .accountUuid()); - assertThat(target.currentSubscriptionVersion()) - .isEqualTo(f.request.expectedSubscriptionVersion()); - callbacks.incrementAndGet(); - return authorized(f); - })); - assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); - assertThat(result.committedRowVersion()).isEqualTo(f.request.expectedSubscriptionVersion() + 2); - assertThat(count(c, "subscription_lifecycle_terminal_resolutions")).isOne(); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); - assertThat(count(c, "account_audit_outbox")).isEqualTo(f.auditRowsBefore + 1); - assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); - assertThat(f.fixture.service().readCurrent(f.request.tenantId()).subscriptionStatus()) - .isEqualTo(Status.CANCELED); - List committed = resolutionImage(c); - var replay = in(c, () -> owner.prepareTerminalResolution(f.request)); - assertThat(replay.replayResult()).isEqualTo(result); - assertThat( - in( - c, - () -> - owner.applyTerminalResolution( - replay, - null, - target -> { - callbacks.incrementAndGet(); - return authorized(f); - }))) - .isEqualTo(result); - assertThat(callbacks).hasValue(2); - assertThat(resolutionImage(c)).isEqualTo(committed); - assertThatThrownBy( - () -> - in( - c, - () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) - .hasMessageContaining("IDEMPOTENCY_CONFLICT"); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription_lifecycle_operations SET state = 'COMMITTED', row_version = row_version + 1 WHERE request_id = ?", - f.request.failedRequestId())); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "DELETE FROM subscription_lifecycle_operator_outbox WHERE request_id = ?", - f.request.failedRequestId())); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription_lifecycle_terminal_resolutions SET audit_reason = 'changed' WHERE resolution_request_id = ?", - f.request.resolutionRequestId())); - assertThat(resolutionImage(c)).isEqualTo(committed); - } - - @Test - void activeUnresolvedStaleAndWrongBindingResolutionEvidenceNeverInvokesAuthorizationOrWrites() { - for (String failure : List.of("active", "unresolved", "stale", "wrong-binding")) { - FailedResolution f = failedResolution(); - Context c = f.fixture.context(); - var prepared = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); - List before = resolutionImage(c); - f.fixture.transport().json = - response(f.fixture, failure.equals("active") ? "active" : "canceled"); - if (failure.equals("unresolved")) f.fixture.transport().failure = mock(StripeException.class); - if (failure.equals("wrong-binding")) - f.fixture.transport().json = - f.fixture.transport().json.replace("price_controlled", "price_other"); - var sdk = f.fixture.observer().observe(prepared.binding()); - if (failure.equals("stale")) f.fixture.clock().advance(Duration.ofSeconds(11)); - AtomicInteger callbacks = new AtomicInteger(); - assertThatThrownBy( - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> { - callbacks.incrementAndGet(); - return authorized(f); - }))) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - assertThat(callbacks).hasValue(0); - assertThat(resolutionImage(c)).isEqualTo(before); - } - } - - @Test - void deniedAuthorizationAndActualDownstreamSqlFailureRetainFailedFenceAndAllOwnerRows() { - FailedResolution f = failedResolution(); - Context c = f.fixture.context(); - var prepared = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); - f.fixture.transport().json = response(f.fixture, "canceled"); - var sdk = f.fixture.observer().observe(prepared.binding()); - List before = resolutionImage(c); - assertThatThrownBy( - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> { - assertThat( - count(c, "subscription_lifecycle_terminal_resolutions")) - .isZero(); - throw new IllegalStateException( - "controlled primary authentication denial"); - }))) - .hasMessage("controlled primary authentication denial"); - assertThat(resolutionImage(c)).isEqualTo(before); - c.setup() - .execute( - "CREATE FUNCTION reject_resolution_billing() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'controlled resolution billing failure' USING ERRCODE = '23514'; END; $$"); - c.setup() - .execute( - "CREATE TRIGGER reject_resolution_billing BEFORE INSERT ON account_tenant_entitlement_outbox_events FOR EACH ROW EXECUTE FUNCTION reject_resolution_billing()"); - assertSqlState( - "23514", - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution(prepared, sdk, target -> authorized(f)))); - assertThat(resolutionImage(c)).isEqualTo(before); - assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET lifecycle_inflight_request_id = NULL, row_version = row_version + 1 WHERE subscription_id = ?", - f.request.subscriptionId())); - assertSqlState( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET lifecycle_inflight_request_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", - UUID.randomUUID(), - f.request.subscriptionId())); - assertThat(resolutionImage(c)).isEqualTo(before); - } - - @Test - void resolutionRequiresExactCapturedVersionsSameOwnerAndMatchingFreshAuthorizationSource() { - FailedResolution f = failedResolution(); - Context c = f.fixture.context(); - List before = resolutionImage(c); - for (String changed : List.of("owner", "failed-version", "subscription-version")) { - Request wrong = - new Request( - f.request.resolutionRequestId(), - f.request.failedRequestId(), - f.request.creationRequestId(), - f.request.subscriptionId(), - f.request.tenantId(), - f.request.expectedFailedOperationVersion() - + (changed.equals("failed-version") ? 1 : 0), - f.request.expectedSubscriptionVersion() - + (changed.equals("subscription-version") ? 1 : 0), - changed.equals("owner") ? UUID.randomUUID() : f.request.actorAccountId(), - f.request.controlUiIssuanceOperationId(), - f.request.controlUiTokenHash(), - f.request.auditEventId(), - f.request.auditReason()); - assertThatThrownBy(() -> in(c, () -> f.fixture.owner().prepareTerminalResolution(wrong))) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - } - var prepared = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); - f.fixture.transport().json = response(f.fixture, "canceled"); - var sdk = f.fixture.observer().observe(prepared.binding()); - assertThatThrownBy( - () -> in(c, () -> f.fixture.owner().applyTerminalResolution(prepared, sdk, null))) - .isInstanceOf(NullPointerException.class); - for (String changed : List.of("actor", "issuance", "hash", "stale-auth")) { - assertThatThrownBy( - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> - new AuthorizedActor( - changed.equals("actor") - ? UUID.randomUUID() - : f.request.actorAccountId(), - changed.equals("issuance") - ? UUID.randomUUID() - : f.request.controlUiIssuanceOperationId(), - changed.equals("hash") - ? "b".repeat(64) - : f.request.controlUiTokenHash(), - changed.equals("stale-auth") - ? f.fixture.clock().instant().minusSeconds(1) - : f.fixture.clock().instant())))) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - } - assertThat(resolutionImage(c)).isEqualTo(before); - } - - @Test - void competingResolutionRequestsCommitExactlyOneAndRejectStaleCapturedTarget() throws Exception { - FailedResolution f = failedResolution(); - Context c = f.fixture.context(); - Request other = - new Request( - UUID.randomUUID(), - f.request.failedRequestId(), - f.request.creationRequestId(), - f.request.subscriptionId(), - f.request.tenantId(), - f.request.expectedFailedOperationVersion(), - f.request.expectedSubscriptionVersion(), - f.request.actorAccountId(), - f.request.controlUiIssuanceOperationId(), - f.request.controlUiTokenHash(), - UUID.randomUUID(), - "second controlled resolution"); - var first = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); - var second = in(c, () -> f.fixture.owner().prepareTerminalResolution(other)); - f.fixture.transport().json = response(f.fixture, "canceled"); - var firstSdk = f.fixture.observer().observe(first.binding()); - var secondSdk = f.fixture.observer().observe(second.binding()); - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch go = new CountDownLatch(1); - var executor = Executors.newFixedThreadPool(2); - try { - var a = - executor.submit( - () -> { - ready.countDown(); - await(go); - return attemptResolution(f, first, firstSdk); - }); - var b = - executor.submit( - () -> { - ready.countDown(); - await(go); - return attemptResolution(f, second, secondSdk); - }); - assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); - go.countDown(); - assertThat(List.of(a.get(20, TimeUnit.SECONDS), b.get(20, TimeUnit.SECONDS))) - .containsExactlyInAnyOrder(true, false); - } finally { - go.countDown(); - executor.shutdownNow(); - } - assertThat(count(c, "subscription_lifecycle_terminal_resolutions")).isOne(); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); - assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); - } - - private static boolean attemptResolution( - FailedResolution f, - AccountHostingSubscriptionLifecycleRepository.ResolutionPreparation prepared, - StripeHostingSubscriptionObserver.Result sdk) { - try { - in( - f.fixture.context(), - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> - new AuthorizedActor( - prepared.request().actorAccountId(), - prepared.request().controlUiIssuanceOperationId(), - prepared.request().controlUiTokenHash(), - f.fixture.clock().instant()))); - return true; - } catch (AccountSubscriptionIntentRepository.FenceRejectedException lostRace) { - return false; - } - } - - private static FailedResolution failedResolution() { - Context c = context("1036"); - Fixture f = fixture(c); - var claim = claim(f); - UUID failed = UUID.randomUUID(); - f.transport().json = response(f, "active").replace("price_controlled", "price_wrong"); - for (int attempt = 1; attempt <= 3; attempt++) { - assertThat( - f.service() - .reconcile(failed, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) - .outcome()) - .isEqualTo(attempt == 3 ? Outcome.TERMINAL_FAILURE : Outcome.RECONCILING); - f.clock().advance(Duration.ofSeconds(2)); - } - long version = - one( - c, - "SELECT row_version FROM subscription_lifecycle_operations WHERE request_id = ?", - failed) - .get(0, Long.class); - long current = - c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); - Request request = - new Request( - UUID.randomUUID(), - failed, - f.creation().requestId(), - f.creation().subscriptionId(), - f.creation().tenantId(), - version, - current, - f.creation().owner().accountUuid(), - UUID.randomUUID(), - "a".repeat(64), - UUID.randomUUID(), - "Controlled canceled provider recovery"); - return new FailedResolution( - f, request, failedImage(c, failed), count(c, "account_audit_outbox")); - } - - private static AuthorizedActor authorized(FailedResolution f) { - return new AuthorizedActor( - f.request.actorAccountId(), - f.request.controlUiIssuanceOperationId(), - f.request.controlUiTokenHash(), - f.fixture.clock().instant()); - } - - private static Request withReason(Request original, String reason) { - return new Request( - original.resolutionRequestId(), - original.failedRequestId(), - original.creationRequestId(), - original.subscriptionId(), - original.tenantId(), - original.expectedFailedOperationVersion(), - original.expectedSubscriptionVersion(), - original.actorAccountId(), - original.controlUiIssuanceOperationId(), - original.controlUiTokenHash(), - original.auditEventId(), - reason); - } - - private static String failedImage(Context c, UUID failed) { - return one( - c, - "SELECT to_jsonb(operation)::text || to_jsonb(notice)::text FROM subscription_lifecycle_operations operation JOIN subscription_lifecycle_operator_outbox notice USING (request_id) WHERE request_id = ?", - failed) - .get(0, String.class); - } - - private static List resolutionImage(Context c) { - List image = new ArrayList<>(); - for (String table : - List.of( - "subscription", - "subscription_current_observations", - "subscription_lifecycle_operations", - "subscription_lifecycle_attempts", - "subscription_lifecycle_observations", - "subscription_lifecycle_receipts", - "subscription_lifecycle_terminal_resolutions", - "subscription_lifecycle_operator_outbox", - "subscription_provider_history", - "subscription_provider_terminal_resolutions", - "subscription_instrument_reservations", - "account_audit_outbox", - "account_tenant_entitlement_outbox_events", - "account_tenant_authority_source_records", - "account_authority_generations")) { - image.add( - one( - c, - "SELECT coalesce(jsonb_agg(to_jsonb(value) ORDER BY to_jsonb(value)::text)::text, '[]') FROM " - + table - + " value") - .get(0, String.class)); - } - return List.copyOf(image); - } - - /** Controlled authorization callback only; no genuine actor/primary-authentication claim. */ - private record FailedResolution( - Fixture fixture, Request request, String failureImage, long auditRowsBefore) {} - - private static void activate(Fixture f) { - var claim = claim(f); - assertThat( - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - } - - private static void refresh(Fixture f) { - long version = - f.context() - .intents() - .findCurrentByTenant(f.creation().tenantId()) - .orElseThrow() - .rowVersion(); - assertThat( - f.service() - .reconcile( - UUID.randomUUID(), f.creation().requestId(), version, f.providerId(), null) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - } - - private static Fixture fixture(Context c) { - long row = ROWS.incrementAndGet(); - UUID account = - one( - c, - "INSERT INTO accounts(username,email,password_hash) VALUES (?, ?, 'controlled-hash') RETURNING account_uuid", - "hosting-" + row, - "hosting-" + row + "@example.test") - .get("account_uuid", UUID.class); - UUID tenant = UUID.randomUUID(); - UUID createRequest = UUID.randomUUID(); - UUID createOperation = UUID.randomUUID(); - String key = "game-" + row; - String requestDigest = - GameTenantCreationDigest.requestDigest( - "prod", createRequest, key, "Controlled hosting", "Storage only"); - var source = - new FreshTenantCreationEvidence( - 1, - "prod", - createRequest, - createOperation, - requestDigest, - tenant, - row, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - "prod", - createRequest, - createOperation, - requestDigest, - tenant, - row, - key, - "NEW_GAME_ROW")); - in( - c, - () -> { - new FreshTenantIdentityAssociationRepository(c.dsl(), "prod").importVerified(source); - return new AccountAuthorityGenerationRepository(c.dsl()).initializeTenantIfAbsent(tenant); - }); - UUID authorization = UUID.randomUUID(); - var creator = - new FreshTenantCreatorEvidence( - 1, - source, - account, - authorization, - DIGEST, - FreshTenantCreatorDigest.evidenceDigest(1, source, account, authorization, DIGEST)); - var owner = - in( - c, - () -> - new AccountInitialTenantBillingOwnerRepository(c.dsl()) - .establishInitial( - new AccountInitialTenantBillingOwnerRepository.InitialRequest( - UUID.randomUUID(), creator, UUID.randomUUID(), 1, true))); - var customers = new AccountBillingCustomerRepository(c.dsl()); - var pendingCustomer = - in(c, () -> customers.retainIntent(account, UUID.randomUUID(), UUID.randomUUID())) - .customer(); - var customer = - in( - c, - () -> - customers.recordObservation( - account, - pendingCustomer.customerProvisioningRequestId(), - 1, - UUID.randomUUID(), - AccountBillingCustomerRecord.Observation.CONFIRMED, - "cus_" + row, - DIGEST)); - var instrument = - in( - c, - () -> - new AccountPaymentInstrumentRepository(c.dsl()) - .retainAttachment( - new AccountPaymentInstrumentRepository.Attachment( - UUID.randomUUID(), - UUID.randomUUID(), - account, - customer.customerProvisioningRequestId(), - customer.providerCustomerId(), - "pm_" + row, - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new AccountPaymentInstrumentRecord.DisplayMetadata( - "visa", "4242", 12, 2030), - DIGEST))); - var creation = - in( - c, - () -> - c.intents() - .retainPending( - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - tenant, - new OwnerFence(account, owner.ownerVersion(), owner.ownerGeneration()), - "hosting", - instrument.instrumentUuid(), - 1, - new ProducerEvidence(account, UUID.randomUUID(), DIGEST), - null))); - var clock = new MutableClock(creation.createdAt().plusSeconds(1)); - var transport = new ControlledTransport(); - var repository = owner(c, clock, c.intents()); - var observer = - new StripeHostingSubscriptionObserver( - new com.stripe.StripeClient(transport), - clock, - Duration.ofMillis(250), - Duration.ofSeconds(1)); - var service = - new AccountHostingSubscriptionLifecycleService( - repository, observer, new DataSourceTransactionManager(c.source())); - Fixture fixture = - new Fixture( - c, creation, instrument, "sub_" + row, clock, transport, repository, observer, service); - transport.json = response(fixture, "active"); - return fixture; - } - - private static AccountHostingSubscriptionLifecycleRepository owner( - Context c, Clock clock, AccountSubscriptionIntentRepository intents) { - return new AccountHostingSubscriptionLifecycleRepository( - c.dsl(), - intents, - clock, - new ReconciliationLimits( - 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), - new AccountHostingSubscriptionLifecyclePolicy( - Duration.ofSeconds(15), - new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120))), - "prod", - false); - } - - private static AccountHostingSubscriptionLifecycleService service( - Context c, - AccountHostingSubscriptionLifecycleRepository owner, - ControlledTransport transport, - Clock clock) { - return new AccountHostingSubscriptionLifecycleService( - owner, - new StripeHostingSubscriptionObserver( - new com.stripe.StripeClient(transport), - clock, - Duration.ofMillis(250), - Duration.ofSeconds(1)), - new DataSourceTransactionManager(c.source())); - } - - @SuppressFBWarnings( - value = "VA_FORMAT_STRING_USES_NEWLINE", - justification = - "This is a JSON test fixture whose text block intentionally retains LF characters independent of the host console line separator.") - private static String response(Fixture f, String status) { - return """ - {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", - "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":null, - "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", - "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, - "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", - "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} - """ - .formatted( - f.providerId(), - f.creation().providerCustomerId(), - f.instrument().providerPaymentMethodId(), - status, - f.creation().subscriptionProvisioningRequestId(), - f.creation().subscriptionId(), - f.providerId(), - f.creation().createdAt().getEpochSecond(), - f.creation().createdAt().getEpochSecond() + 3600, - f.creation().planQuote().providerPriceId()); - } - - private static Context context(String target) { - String schema = "hosting_lifecycle_" + UUID.randomUUID().toString().replace("-", ""); - var source = - new DriverManagerDataSource( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - source.setSchema(schema); - var setup = DSL.using(source, SQLDialect.POSTGRES); - var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); - var tx = new TransactionTemplate(new DataSourceTransactionManager(source)); - var catalog = - new AccountHostingPlanCatalog( - List.of( - new AccountHostingPlanCatalog.ConfiguredPlan( - "hosting", "price_controlled", "1", "100", "2", "1048576"))); - var c = - new Context( - source, schema, setup, dsl, tx, new AccountSubscriptionIntentRepository(dsl, catalog)); - configuration(c).target(target).load().migrate(); - return c; - } - - private static FluentConfiguration configuration(Context c) { - return Flyway.configure() - .dataSource(c.source()) - .schemas(c.schema()) - .defaultSchema(c.schema()) - .placeholders(Map.of("serviceSchema", c.schema())) - .locations("classpath:db/migration", "classpath:db/migration/saga"); - } - - private static T in(Context c, Supplier body) { - return Objects.requireNonNull(c.tx().execute(s -> body.get())); - } - - private static org.jooq.Record one(Context c, String sql, Object... bindings) { - return Objects.requireNonNull(c.setup().fetchOne(sql, bindings)); - } - - private static long count(Context c, String table) { - return one(c, "SELECT count(*) FROM " + table).get(0, Long.class); - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Controlled SDK read barrier timed out"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Controlled SDK read interrupted", interrupted); - } - } - - private static void assertSqlState(String state, Runnable body) { - assertThatThrownBy(body::run) - .satisfies( - failure -> { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - assertThat(sql.getSQLState()).isEqualTo(state); - return; - } - } - throw new AssertionError("Expected actual PostgreSQL constraint refusal", failure); - }); - } - - private record Context( - DriverManagerDataSource source, - String schema, - DSLContext setup, - DSLContext dsl, - TransactionTemplate tx, - AccountSubscriptionIntentRepository intents) {} - - private record Fixture( - Context context, - AccountSubscriptionCreationRecord creation, - AccountPaymentInstrumentRecord instrument, - String providerId, - MutableClock clock, - ControlledTransport transport, - AccountHostingSubscriptionLifecycleRepository owner, - StripeHostingSubscriptionObserver observer, - AccountHostingSubscriptionLifecycleService service) {} - - private static final class MutableClock extends Clock { - private Instant current; - - MutableClock(Instant current) { - this.current = current; - } - - void advance(Duration amount) { - current = current.plus(amount); - } - - @Override - public ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return current; - } - } - - private static final class ControlledTransport implements StripeResponseGetter { - private String json; - private StripeException failure; - private Runnable duringRead; - private int reads; - - @Override - @SuppressWarnings("unchecked") - public T request( - BaseAddress address, - RequestMethod method, - String path, - Map params, - Type type, - RequestOptions options, - ApiMode mode) - throws StripeException { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(method).isEqualTo(RequestMethod.GET); - assertThat(path).startsWith("/v1/subscriptions/"); - reads++; - Runnable action = duringRead; - duringRead = null; - if (action != null) { - action.run(); - } - if (failure != null) { - throw failure; - } - return (T) com.stripe.net.ApiResource.GSON.fromJson(json, type); - } - - @Override - public InputStream requestStream( - BaseAddress address, - RequestMethod method, - String path, - Map params, - RequestOptions options, - ApiMode mode) - throws StripeException { - throw new AssertionError("No streaming or provider mutations are allowed"); - } - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java deleted file mode 100644 index 8ac4a906e7..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java +++ /dev/null @@ -1,1883 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.sql.SQLException; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; -import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.DisplayMetadata; -import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRepository.Attachment; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ReplacementFence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.ConflictException; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.MappingDisposition; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.test.TestContainerImages; -import org.assertj.core.api.ThrowableAssert.ThrowingCallable; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.configuration.FluentConfiguration; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionTemplate; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Actual PostgreSQL persistence/concurrency sources using CONTROLLED owner/provider evidence. These - * fixtures do not qualify genuine authenticated producers, Stripe, lifecycle/outbox dispatch, - * transfers, downstream readers or production admission. No trigger is disabled to construct them. - */ -@Testcontainers(disabledWithoutDocker = true) -class AccountSubscriptionIntentPostgresIntegrationTest { - private static final String DIGEST = "sha256:" + "a".repeat(64); - private static final OffsetDateTime BOUNDARY = OffsetDateTime.parse("2026-11-01T00:00:00Z"); - private static final AtomicLong GAME_ROWS = new AtomicLong(100); - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void durableProvisioningClaimReplaysAfterRecreationAndRecoversOnlyTheOriginalBinding() { - Context c = context(); - configuration(c).target("1030").load().migrate(); - Seed seed = seed(c); - var created = create(c, request(seed, UUID.randomUUID(), 1, null)); - Instant start = created.createdAt().plusSeconds(1); - UUID attemptId = UUID.randomUUID(); - var first = - Objects.requireNonNull( - c.tx().execute(s -> lifecycle(c, start).claim(created.requestId(), 1, attemptId))) - .claim(); - assertThat(first.creation()).isEqualTo(created); - assertThat(first.subscriptionRowVersion()).isEqualTo(2); - assertThat(first.attemptNumber()).isEqualTo(1); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("provisioning"); - assertThat( - c.repository() - .findCurrentByTenant(seed.tenant()) - .orElseThrow() - .providerSubscriptionId()) - .isNull(); - var replay = - Objects.requireNonNull( - c.tx().execute(s -> lifecycle(c, start).claim(created.requestId(), 1, attemptId))) - .claim(); - assertThat(replay.attemptId()).isEqualTo(first.attemptId()); - assertThat(replay.subscriptionRowVersion()).isEqualTo(first.subscriptionRowVersion()); - assertThat(replay.expiresAt()).isEqualTo(first.expiresAt()); - assertThat(count(c, "subscription_provisioning_attempts")).isOne(); - var waiting = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, start.plusSeconds(5)) - .claim(created.requestId(), 2, UUID.randomUUID()))); - assertThat(waiting.disposition()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); - Instant recoveryTime = start.plusSeconds(12); - var recovered = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, recoveryTime) - .claim(created.requestId(), 2, UUID.randomUUID()))) - .claim(); - // Attempt history does not grant provider IO; the independent dispatch receipt owns it. - assertThat(recovered.attemptNumber()).isEqualTo(2); - assertThat(recovered.creation()).isEqualTo(created); - assertThat(recovered.subscriptionRowVersion()).isEqualTo(3); - assertThat(recovered.attemptId()).isNotEqualTo(first.attemptId()); - assertThat(count(c, "subscription_provisioning_attempts")).isEqualTo(2); - assertThatThrownBy(() -> c.tx().execute(s -> lifecycle(c, recoveryTime).deferUnresolved(first))) - .isInstanceOf(FenceRejectedException.class); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - created.requestId()), - "Expected retained reservation") - .get("released_at")) - .isNull(); - assertThat(count(c, "subscription_provider_history")).isZero(); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isZero(); - } - - @Test - void provisioningExhaustionCommitsOneOperatorItemWithoutCancellationOrWalletRewrite() { - Context c = context(); - configuration(c).target("1030").load().migrate(); - Seed seed = seed(c); - var created = create(c, request(seed, UUID.randomUUID(), 1, null)); - Instant start = created.createdAt().plusSeconds(1); - var first = - Objects.requireNonNull( - c.tx() - .execute( - s -> lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()))) - .claim(); - var firstDeferred = c.tx().execute(s -> lifecycle(c, start).deferUnresolved(first)); - assertThat(firstDeferred) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); - Instant retryAt = start.plusSeconds(1); - var second = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, retryAt).claim(created.requestId(), 2, UUID.randomUUID()))) - .claim(); - var exhausted = c.tx().execute(s -> lifecycle(c, retryAt).deferUnresolved(second)); - assertThat(exhausted) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - var exhaustedReplay = c.tx().execute(s -> lifecycle(c, retryAt).deferUnresolved(second)); - assertThat(exhaustedReplay) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); - var current = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); - assertThat(current.status()).isEqualTo("provisioning"); - assertThat(current.terminalResolutionId()).isNull(); - assertThat(current.rowVersion()).isEqualTo(3); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT row_version FROM payment_instrument WHERE instrument_uuid = ?", - seed.instrument().instrumentUuid()), - "Expected retained instrument") - .get("row_version", Long.class)) - .isOne(); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - created.requestId()), - "Expected retained reservation") - .get("released_at")) - .isNull(); - rejectSql( - "23514", - () -> - c.setup() - .execute("UPDATE subscription_provisioning_operator_outbox SET reason = reason")); - rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription_provisioning_attempts")); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.EnumSource( - value = AccountPaymentInstrumentRecord.State.class, - names = {"ATTACHABLE", "UNAVAILABLE"}) - void claimRollbackAndStaleReservedWalletRetainOneTerminalOperatorItem( - AccountPaymentInstrumentRecord.State observedState) { - Context c = context(); - configuration(c).target("1030").load().migrate(); - Seed seed = seed(c); - var created = create(c, request(seed, UUID.randomUUID(), 1, null)); - Instant start = created.createdAt().plusSeconds(1); - c.tx() - .executeWithoutResult( - s -> { - lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()); - s.setRollbackOnly(); - }); - assertThat(count(c, "subscription_provisioning_work")).isZero(); - assertThat(count(c, "subscription_provisioning_attempts")).isZero(); - var pending = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); - assertThat(pending.status()).isEqualTo("pending"); - var observed = - c.tx() - .execute( - s -> - new AccountPaymentInstrumentRepository(c.dsl()) - .recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - seed.instrument().instrumentUuid(), - seed.owner().accountUuid(), - 1L, - observedState, - seed.instrument().display(), - DIGEST))); - // Upgrade the original pending intent and its changed wallet without recreating either row. - configuration(c).load().migrate(); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> lifecycle(c, start).claim(created.requestId(), 2, UUID.randomUUID()))) - .isInstanceOf(FenceRejectedException.class); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> - lifecycle(c, created.createdAt().minusSeconds(1)) - .claim(created.requestId(), 1, UUID.randomUUID()))) - .isInstanceOf(FenceRejectedException.class); - c.tx() - .executeWithoutResult( - s -> { - assertThat( - lifecycle(c, start) - .claim(created.requestId(), 1, UUID.randomUUID()) - .disposition()) - .isEqualTo( - AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - s.setRollbackOnly(); - }); - assertThat(count(c, "subscription_provisioning_work")).isZero(); - assertThat(count(c, "subscription_provisioning_operator_outbox")).isZero(); - UUID firstAttempt = UUID.randomUUID(); - for (UUID attempt : List.of(firstAttempt, firstAttempt, UUID.randomUUID())) { - var result = - Objects.requireNonNull( - c.tx().execute(s -> lifecycle(c, start).claim(created.requestId(), 1, attempt))); - assertThat(result.disposition()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - assertThat(result.claim()).isNull(); - } - assertThat( - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, start.plusSeconds(7200)) - .claim(created.requestId(), 1, UUID.randomUUID()))) - .disposition()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - assertThat(count(c, "subscription_provisioning_work")).isOne(); - assertThat(count(c, "subscription_provisioning_attempts")).isZero(); - assertThat(count(c, "subscription_provider_dispatch_claim")).isZero(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); - assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); - var work = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_provisioning_work WHERE request_id = ?", - created.requestId())); - assertThat(work.get("phase", String.class)) - .isEqualTo("BILLING_RECONCILIATION_TERMINAL_FAILURE"); - assertThat(work.get("attempt_count", Integer.class)).isZero(); - assertThat(work.get("row_version", Long.class)).isEqualTo(2L); - assertThat(work.get("last_attempt_id")).isNull(); - var notice = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_provisioning_operator_outbox WHERE request_id = ?", - created.requestId())); - assertThat(notice.get("reason", String.class)).isEqualTo("RESERVED_INSTRUMENT_CHANGED"); - assertThat(notice.get("recorded_at")).isEqualTo(work.get("terminal_at")); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow()).isEqualTo(pending); - assertThat( - new AccountPaymentInstrumentRepository(c.dsl()) - .findByOwner(seed.owner().accountUuid(), seed.instrument().instrumentUuid()) - .orElseThrow()) - .isEqualTo(observed); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - created.requestId())) - .get("released_at")) - .isNull(); - } - - @Test - void concurrentProvisioningClaimsHaveOneCurrentVersionWinner() throws Exception { - Context c = context(); - configuration(c).target("1030").load().migrate(); - Seed seed = seed(c); - var created = create(c, request(seed, UUID.randomUUID(), 1, null)); - Instant start = created.createdAt().plusSeconds(1); - Supplier attempt = - () -> { - try { - return Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, start) - .claim(created.requestId(), 1, UUID.randomUUID()))) - .disposition() - .name(); - } catch (FenceRejectedException stale) { - return "FENCED"; - } - }; - assertThat(race(attempt, attempt)).containsExactlyInAnyOrder("CLAIMED", "FENCED"); - assertThat(count(c, "subscription_provisioning_attempts")).isOne(); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().rowVersion()) - .isEqualTo(2); - } - - @Test - void expiredIntentCreatesUnresolvedFailureWithoutClaimingProviderWork() { - Context c = context(); - configuration(c).target("1030").load().migrate(); - Seed seed = seed(c); - var created = create(c, request(seed, UUID.randomUUID(), 1, null)); - var expired = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, created.createdAt().plusSeconds(3600)) - .claim(created.requestId(), 1, UUID.randomUUID()))); - assertThat(expired.disposition()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - assertThat(expired.claim()).isNull(); - assertThat(count(c, "subscription_provisioning_attempts")).isZero(); - assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("pending"); - } - - private static AccountHostingSubscriptionLifecycleRepository lifecycle(Context c, Instant now) { - return new AccountHostingSubscriptionLifecycleRepository( - c.dsl(), - c.repository(), - Clock.fixed(now, ZoneOffset.UTC), - new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( - 2, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), - new AccountHostingSubscriptionLifecyclePolicy( - Duration.ofSeconds(15), - new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( - Duration.ofSeconds(60), Duration.ofSeconds(120))), - "prod", - false); - } - - @Test - void - combinedForwardUpgradePreservesOriginalNumericRowsAndPublishedHistoryWithoutInferringWinners() { - Context c = predecessor(); - var rows = - c.setup() - .fetch( - "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM subscription s ORDER BY id") - .intoMaps(); - var accounts = - c.setup() - .fetch( - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") - .intoMaps(); - var history = - c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); - - configuration(c).target("1029").load().migrate(); - - assertThat( - c.setup() - .fetch( - "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM account_retained_subscription_evidence s ORDER BY id") - .intoMaps()) - .isEqualTo(rows); - assertThat( - c.setup() - .fetch( - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") - .intoMaps()) - .isEqualTo(accounts); - var afterHistory = - c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); - assertThat(afterHistory).hasSize(history.size() + 5); - assertThat(afterHistory.subList(history.size(), afterHistory.size())) - .extracting(row -> row.get("version")) - .containsExactly("1027", "1027.1", "1027.2", "1028", "1029"); - assertThat(afterHistory.subList(0, history.size())).containsExactlyElementsOf(history); - assertThat( - c.setup() - .fetch( - "SELECT version FROM flyway_schema_history WHERE version IN ('1000','1001','1002')")) - .hasSize(3); - assertThat(count(c, "subscription")).isZero(); - assertThat(count(c, "subscription_create_operations")).isZero(); - assertThat(count(c, "subscription_provider_history")).isZero(); - assertThat( - c.setup() - .fetch( - "SELECT tenant_id FROM subscription WHERE superseded_at IS NULL GROUP BY tenant_id HAVING count(*) > 1")) - .isEmpty(); - assertThat( - c.setup() - .fetch( - "SELECT provider_subscription_id FROM subscription WHERE superseded_at IS NULL AND provider_subscription_id IS NOT NULL GROUP BY provider_subscription_id HAVING count(*) <> 1")) - .isEmpty(); - assertThat(indexDefinition(c, "uq_subscription_active_tenant")) - .contains("UNIQUE", "tenant_id", "superseded_at IS NULL"); - assertThat(indexDefinition(c, "uq_subscription_active_provider")) - .contains("UNIQUE", "provider_subscription_id IS NOT NULL", "superseded_at IS NULL"); - rejectSql( - "23514", - () -> - c.setup().execute("UPDATE account_retained_subscription_evidence SET status = status")); - configuration(c).target("1029").load().validate(); - } - - @Test - void - pendingRetainsExactOriginalResultSeparateIdentitiesReservationAndOutboxAndRejectsChangedRequest() { - Context c = context(); - Seed seed = seed(c); - var request = request(seed, UUID.randomUUID(), 1, null); - var created = create(c, request); - assertThat(created.requestDigest()) - .isEqualTo( - AccountSubscriptionCreateDigest.encode( - seed.tenant(), c.account(), "basic-hosting", seed.instrument().instrumentUuid()) - .digest()); - assertThat(created.initialStatus()).isEqualTo("pending"); - assertThat(created.initialRowVersion()).isOne(); - assertThat( - List.of( - created.requestId(), - created.subscriptionProvisioningRequestId(), - created.cleanupProviderIdentity(), - created.customerProvisioningRequestId())) - .doesNotHaveDuplicates(); - var customer = - new AccountBillingCustomerRepository(c.dsl()).findByAccount(c.account()).orElseThrow(); - assertThat(created.subscriptionProvisioningRequestId()) - .isNotEqualTo(customer.providerIdempotencyId()); - assertThat(created.cleanupProviderIdentity()).isNotEqualTo(customer.providerIdempotencyId()); - assertThat( - c.repository() - .findCurrentByTenant(seed.tenant()) - .orElseThrow() - .providerSubscriptionId()) - .isNull(); - assertThat( - Objects.requireNonNull( - c.tx().execute(s -> c.repository().lockPendingForClaim(request.requestId(), 1))) - .status()) - .isEqualTo("pending"); - assertThat(create(c, request)).isEqualTo(created); - assertThat(count(c, "subscription_create_outbox")).isOne(); - assertThat(count(c, "subscription_instrument_reservations")).isOne(); - assertThat(count(c, "subscription_create_provider_identities")).isEqualTo(2); - var changed = - new AccountSubscriptionCreateRequest( - request.requestId(), - seed.tenant(), - seed.owner(), - "pro-hosting", - seed.instrument().instrumentUuid(), - 1, - producer(c.account()), - null); - assertThatThrownBy(() -> create(c, changed)) - .isInstanceOf(ConflictException.class) - .hasMessageContaining("IDEMPOTENCY_CONFLICT"); - assertThat(count(c, "subscription")).isOne(); - controlledTerminalCleanup(c, created); - assertThat(create(c, request)) - .isEqualTo(created); // Never rebuild the result from canceled current state. - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("canceled"); - } - - @Test - void - frozenServerQuoteReplaysAfterCatalogChangeOrRemovalWithoutChangingCallerDigestOrReservation() { - Context c = context(); - Seed first = seed(c); - var request = request(first, UUID.randomUUID(), 1, null); - var created = create(c, request); - var quote = configuredPlans().resolve("basic-hosting"); - assertThat(created.planQuote()).isEqualTo(quote); - var retained = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_create_operations WHERE request_id = ?", - created.requestId())); - assertThat(retained.get("plan_quote_payload", byte[].class)).containsExactly(quote.payload()); - assertThat(retained.get("plan_quote_digest", String.class)).isEqualTo(quote.digest()); - assertThat(retained.get("provider_price_id", String.class)).isEqualTo(quote.providerPriceId()); - assertThat(retained.get("provider_quantity", Long.class)).isEqualTo(quote.providerQuantity()); - assertThat(retained.get("max_active_sessions", Long.class)) - .isEqualTo(quote.maxActiveSessions()); - assertThat(retained.get("max_concurrent_game_instances", Long.class)) - .isEqualTo(quote.maxConcurrentGameInstances()); - assertThat(retained.get("max_storage_bytes", Long.class)).isEqualTo(quote.maxStorageBytes()); - var changedCatalog = - new AccountHostingPlanCatalog( - List.of( - new AccountHostingPlanCatalog.ConfiguredPlan( - "basic-hosting", "price_controlledLater", "9", "200", "4", "2097152"))); - var changedRepository = new AccountSubscriptionIntentRepository(c.dsl(), changedCatalog); - assertThat( - c.tx() - .execute( - s -> changedRepository.retainPending(request))) - .isEqualTo(created); - var removedCatalogRepository = - new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); - assertThat( - c.tx() - .execute( - s -> removedCatalogRepository.retainPending(request))) - .isEqualTo(created); - assertThat(changedRepository.findCurrentByTenant(first.tenant()).orElseThrow().planQuote()) - .isEqualTo(quote); - assertThat( - Objects.requireNonNull( - c.tx() - .execute( - s -> changedRepository.lockPendingForClaim(request.requestId(), 1))) - .planQuote()) - .isEqualTo(quote); - Seed second = seed(c); - var later = - Objects.requireNonNull( - c.tx() - .execute( - s -> - changedRepository.retainPending( - request(second, UUID.randomUUID(), 1, null)))); - assertThat(later.planQuote()).isEqualTo(changedCatalog.resolve("basic-hosting")); - assertThat(later.planQuote().digest()).isNotEqualTo(created.planQuote().digest()); - assertThat(created.requestDigest()) - .isEqualTo( - AccountSubscriptionCreateDigest.encode( - first.tenant(), - first.owner().accountUuid(), - request.planCode(), - request.paymentInstrumentId()) - .digest()); - var conflict = - new AccountSubscriptionCreateRequest( - request.requestId(), - request.tenantId(), - request.owner(), - "pro-hosting", - request.paymentInstrumentId(), - request.instrumentVersion(), - request.producer(), - null); - assertThatThrownBy(() -> c.tx().execute(s -> changedRepository.retainPending(conflict))) - .isInstanceOf(ConflictException.class) - .hasMessageContaining("IDEMPOTENCY_CONFLICT"); - assertThat(count(c, "subscription_create_operations")).isEqualTo(2); - assertThat(count(c, "subscription_instrument_reservations")).isEqualTo(2); - assertThat(count(c, "subscription_create_outbox")).isEqualTo(2); - assertThat(count(c, "subscription_provider_history")).isZero(); - assertThat(changedRepository.findCreation(request.requestId())).contains(created); - } - - @Test - void missingServerPlanConfigurationCreatesNoIntentReservationOrWorkItem() { - Context c = context(); - Seed seed = seed(c); - var unconfigured = - new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> unconfigured.retainPending(request(seed, UUID.randomUUID(), 1, null)))) - .isInstanceOf(AccountHostingPlanCatalog.PlanUnavailableException.class); - assertThat(count(c, "subscription_create_operations")).isZero(); - assertThat(count(c, "subscription")).isZero(); - assertThat(count(c, "subscription_instrument_reservations")).isZero(); - assertThat(count(c, "subscription_create_outbox")).isZero(); - } - - @Test - void directSqlQuoteBytesDigestAndProjectedFieldsMustAgreeAndRetainedQuoteCannotBeRewritten() { - Context c = context(); - Seed seed = seed(c); - var request = request(seed, UUID.randomUUID(), 1, null); - var quote = configuredPlans().resolve(request.planCode()); - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> - insertBareOperationWithQuote( - c, - request, - seed, - UUID.randomUUID(), - UUID.randomUUID(), - quote, - quote.payload(), - "sha256:" + "0".repeat(64)))); - for (var changedFields : - List.of( - new AccountHostingPlanQuote( - quote.planCode(), "price_substituted", quote.providerQuantity(), 100, 2, 1048576), - new AccountHostingPlanQuote( - quote.planCode(), quote.providerPriceId(), 2, 100, 2, 1048576), - new AccountHostingPlanQuote( - quote.planCode(), - quote.providerPriceId(), - quote.providerQuantity(), - 101, - 2, - 1048576), - new AccountHostingPlanQuote( - quote.planCode(), - quote.providerPriceId(), - quote.providerQuantity(), - 100, - 3, - 1048576), - new AccountHostingPlanQuote( - quote.planCode(), - quote.providerPriceId(), - quote.providerQuantity(), - 100, - 2, - 1048577))) { - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> - insertBareOperationWithQuote( - c, - request, - seed, - UUID.randomUUID(), - UUID.randomUUID(), - changedFields, - quote.payload(), - quote.digest()))); - } - byte[] alteredBytes = Arrays.copyOf(quote.payload(), quote.payload().length + 1); - alteredBytes[alteredBytes.length - 1] = ' '; - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> - insertBareOperationWithQuote( - c, - request, - seed, - UUID.randomUUID(), - UUID.randomUUID(), - quote, - alteredBytes, - quote.digest()))); - assertThat(count(c, "subscription_create_operations")).isZero(); - var created = create(c, request); - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription_create_operations SET provider_quantity = 2 WHERE request_id = ?", - request.requestId())); - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET plan_quote_digest = ?, row_version = row_version + 1 WHERE subscription_id = ?", - "sha256:" + "f".repeat(64), - created.subscriptionId())); - assertThat(c.repository().findCreation(request.requestId())).contains(created); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().planQuote()) - .isEqualTo(quote); - } - - @Test - void concurrentEmptyTenantCreatesHaveOneWinnerAndConcurrentExactRetriesReplayOneResult() - throws Exception { - Context c = context(); - Seed seed = seed(c); - var request = request(seed, UUID.randomUUID(), 1, null); - List retries = - race(() -> create(c, request), () -> create(c, request)); - assertThat(retries.getLast()).isEqualTo(retries.getFirst()); - assertThat(count(c, "subscription")).isOne(); - Seed empty = seed(c); - var left = request(empty, UUID.randomUUID(), 1, null); - var right = request(empty, UUID.randomUUID(), 1, null); - assertThat(race(() -> attemptCreate(c, left), () -> attemptCreate(c, right))) - .containsExactlyInAnyOrder("APPLIED", "CONFLICT"); - assertThat( - c.setup() - .fetch( - "SELECT * FROM subscription WHERE tenant_id = ? AND superseded_at IS NULL", - empty.tenant())) - .hasSize(1); - assertThat(count(c, "subscription_create_outbox")).isEqualTo(2); - } - - @Test - void unauditedOwnerAdvanceIsRefusedAndStaleOwnerCapturesCannotCreateIntent() { - Context c = context(); - Seed seed = seed(c); - var before = - c.setup() - .fetch( - "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM account_tenant_billing_owners o WHERE tenant_uuid = ?", - seed.tenant()) - .intoMaps(); - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - status -> - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - seed.tenant()))); - assertThat( - c.setup() - .fetch( - "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM account_tenant_billing_owners o WHERE tenant_uuid = ?", - seed.tenant()) - .intoMaps()) - .isEqualTo(before); - // These are stale comparison inputs, not a fabricated committed transfer or authority grant. - for (var stale : - List.of( - new OwnerFence( - seed.owner().accountUuid(), seed.owner().version() + 1, seed.owner().generation()), - new OwnerFence( - seed.owner().accountUuid(), seed.owner().version(), UUID.randomUUID()))) { - var captured = new Seed(seed.tenant(), stale, seed.instrument()); - assertThat(attemptCreate(c, request(captured, UUID.randomUUID(), 1, null))) - .isEqualTo("FENCED"); - } - assertThat(count(c, "subscription_create_operations")).isZero(); - assertThat(count(c, "subscription_create_outbox")).isZero(); - assertThat(count(c, "subscription_instrument_reservations")).isZero(); - } - - @Test - void instrumentAdvanceThatCommitsFirstFencesQueuedCreateWithoutPartialIntent() throws Exception { - Context walletContext = context(); - Seed walletSeed = seed(walletContext); - var walletRequest = request(walletSeed, UUID.randomUUID(), 1, null); - advanceBeforeCreate( - walletContext, - walletRequest, - () -> - new AccountPaymentInstrumentRepository(walletContext.dsl()) - .recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - walletSeed.instrument().instrumentUuid(), - walletContext.account(), - 1, - AccountPaymentInstrumentRecord.State.UNAVAILABLE, - walletSeed.instrument().display(), - DIGEST))); - assertThat(count(walletContext, "subscription_create_operations")).isZero(); - assertThat(count(walletContext, "subscription_create_outbox")).isZero(); - assertThat(count(walletContext, "subscription_instrument_reservations")).isZero(); - } - - @Test - void commitRechecksSameTransactionOwnerAndWalletChangesAndClaimReadRejectsStaleReservation() { - Context c = context(); - Seed seed = seed(c); - var request = request(seed, UUID.randomUUID(), 1, null); - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> { - c.repository().retainPending(request); - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - seed.tenant()); - })); - assertThat(count(c, "subscription")).isZero(); - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> { - c.repository().retainPending(request); - advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID()); - })); - assertThat(count(c, "subscription_create_operations")).isZero(); - create(c, request); - c.tx() - .executeWithoutResult( - s -> advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID())); - assertThatThrownBy( - () -> c.tx().execute(s -> c.repository().lockPendingForClaim(request.requestId(), 1))) - .isInstanceOf(FenceRejectedException.class); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("pending"); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - request.requestId()), - "Expected retained reservation") - .get(0)) - .isNull(); - } - - @Test - void canceledCurrentReplacementIsAtomicVersionedDistinctAndOneConcurrentReplacementWins() - throws Exception { - Context c = context(); - Seed seed = seed(c); - var originalRequest = request(seed, UUID.randomUUID(), 1, null); - var original = create(c, originalRequest); - controlledTerminalCleanup(c, original); - var canceled = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); - var replacement = - request( - seed, - UUID.randomUUID(), - 1, - new ReplacementFence(original.subscriptionId(), canceled.rowVersion())); - c.tx() - .executeWithoutResult( - s -> { - c.repository().retainPending(replacement); - s.setRollbackOnly(); - }); - assertThat(c.repository().findCurrentByTenant(seed.tenant())).contains(canceled); - assertThat(count(c, "subscription")).isOne(); - assertThat(count(c, "subscription_current_observations")).isEqualTo(2); - var stale = - request(seed, UUID.randomUUID(), 1, new ReplacementFence(original.subscriptionId(), 1)); - assertThatThrownBy(() -> create(c, stale)).isInstanceOf(FenceRejectedException.class); - var competing = - request( - seed, - UUID.randomUUID(), - 1, - new ReplacementFence(original.subscriptionId(), canceled.rowVersion())); - assertThat(race(() -> attemptCreate(c, replacement), () -> attemptCreate(c, competing))) - .containsExactlyInAnyOrder("APPLIED", "FENCED"); - var current = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); - assertThat(current.subscriptionId()).isNotEqualTo(original.subscriptionId()); - var successor = c.repository().findCreation(current.creationRequestId()).orElseThrow(); - assertThat(successor.subscriptionProvisioningRequestId()) - .isNotEqualTo(original.subscriptionProvisioningRequestId()); - assertThat(successor.cleanupProviderIdentity()) - .isNotIn(original.subscriptionProvisioningRequestId(), original.cleanupProviderIdentity()); - var retained = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription WHERE subscription_id = ?", - original.subscriptionId())); - assertThat(retained.get("superseded_at")).isNotNull(); - assertThat(retained.get("superseded_by_request_id", UUID.class)) - .isEqualTo(current.creationRequestId()); - assertThat(retained.get("row_version", Long.class)).isEqualTo(canceled.rowVersion() + 1); - assertThat(create(c, originalRequest)).isEqualTo(original); - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET row_version = row_version + 1 WHERE subscription_id = ?", - original.subscriptionId())); - } - - @Test - void directSqlRejectsIdentityMutationDuplicateCurrentProviderAndUnconfirmedActiveState() { - Context c = context(); - Seed first = seed(c); - Seed second = seed(c); - var one = create(c, request(first, UUID.randomUUID(), 1, null)); - var two = create(c, request(second, UUID.randomUUID(), 1, null)); - for (String assignment : - List.of( - "subscription_id = '11111111-1111-4111-8111-111111111111'::uuid", - "tenant_id = '22222222-2222-4222-8222-222222222222'::uuid", - "plan_code = 'other-plan'", - "account_uuid = '33333333-3333-4333-8333-333333333333'::uuid", - "payment_instrument_id = '44444444-4444-4444-8444-444444444444'::uuid")) { - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET " - + assignment - + ", row_version = row_version + 1 WHERE subscription_id = ?", - one.subscriptionId())); - } - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", - one.subscriptionId())); - rejectSql( - "23505", - () -> - c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_duplicate', row_version = row_version + 1 WHERE subscription_id IN (?, ?)", - one.subscriptionId(), - two.subscriptionId()))); - rejectSql( - "23503", - () -> - c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_unmapped', row_version = row_version + 1 WHERE subscription_id = ?", - one.subscriptionId()))); - var duplicateTenant = request(first, UUID.randomUUID(), 1, null); - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> - insertBareOperation( - c, duplicateTenant, first, UUID.randomUUID(), UUID.randomUUID()))); - assertThat(indexDefinition(c, "uq_subscription_active_tenant")) - .contains("UNIQUE", "superseded_at IS NULL"); - assertThat( - c.repository() - .findCurrentByTenant(first.tenant()) - .orElseThrow() - .providerSubscriptionId()) - .isNull(); - assertThat( - c.repository() - .findCurrentByTenant(second.tenant()) - .orElseThrow() - .providerSubscriptionId()) - .isNull(); - } - - @Test - void - operationSubscriptionReservationAndOutboxCannotCommitPartiallyAndCrossRoleKeysCannotBeReused() { - Context c = context(); - Seed first = seed(c); - var created = create(c, request(first, UUID.randomUUID(), 1, null)); - Seed empty = seed(c); - var missingPair = request(empty, UUID.randomUUID(), 1, null); - rejectSql( - "23503", - () -> - c.tx() - .executeWithoutResult( - s -> - insertBareOperation( - c, missingPair, empty, UUID.randomUUID(), UUID.randomUUID()))); - assertThat(c.repository().findCreation(missingPair.requestId())).isEmpty(); - rejectSql( - "23505", - () -> - c.tx() - .executeWithoutResult( - s -> - insertBareOperation( - c, - request(empty, UUID.randomUUID(), 1, null), - empty, - created.cleanupProviderIdentity(), - UUID.randomUUID()))); - for (String table : - List.of( - "subscription_create_operations", - "subscription_create_outbox", - "subscription_create_provider_identities")) { - rejectSql("23514", () -> c.setup().execute("DELETE FROM " + table)); - rejectSql("23514", () -> c.setup().execute("TRUNCATE " + table + " CASCADE")); - } - rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription")); - rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription_instrument_reservations")); - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription_create_operations SET request_digest = request_digest")); - assertThat(count(c, "subscription_create_operations")).isOne(); - assertThat(count(c, "subscription_create_outbox")).isOne(); - } - - @Test - void - canceledCommitRequiresSeparateTerminalEvidenceAndExactInstrumentReleaseInTheSameTransaction() { - Context c = context(); - Seed seed = seed(c); - var creation = create(c, request(seed, UUID.randomUUID(), 1, null)); - rejectSql( - "23514", - () -> - c.tx() - .executeWithoutResult( - s -> { - c.repository().lockPendingForClaim(creation.requestId(), 1); - UUID resolution = UUID.randomUUID(); - c.dsl() - .execute( - "INSERT INTO subscription_provider_terminal_resolutions " - + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,outcome,effective_at,evidence_digest) " - + "VALUES (?, ?, ?, ?, 'PROVIDER_ABSENT', ?::timestamptz, ?)", - resolution, - creation.requestId(), - creation.subscriptionId(), - creation.cleanupProviderIdentity(), - BOUNDARY, - DIGEST); - c.dsl() - .execute( - "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", - resolution, - creation.subscriptionId()); - })); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("pending"); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); - controlledTerminalCleanup(c, creation); - rejectSql("23514", () -> controlledProviderHistory(c, creation, "sub_afterTerminalAbsence")); - assertThat(c.repository().lookupProviderId("sub_afterTerminalAbsence").disposition()) - .isEqualTo(MappingDisposition.UNRESOLVED); - } - - @Test - void terminalCleanupAfterWalletAdvanceReleasesOnlyItsOriginalReservationWithoutRewritingWallet() { - Context c = context(); - Seed first = seed(c); - var originalRequest = request(first, UUID.randomUUID(), 1, null); - var original = create(c, originalRequest); - var instruments = new AccountPaymentInstrumentRepository(c.dsl()); - var advancedWallet = - Objects.requireNonNull( - c.tx() - .execute( - s -> - instruments.recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - first.instrument().instrumentUuid(), - c.account(), - 1, - AccountPaymentInstrumentRecord.State.ATTACHABLE, - first.instrument().display(), - "sha256:" + "b".repeat(64))))); - assertThat(advancedWallet.rowVersion()).isEqualTo(2); - Seed otherTenant = seed(c); - Seed sharedWallet = new Seed(otherTenant.tenant(), otherTenant.owner(), first.instrument()); - var independent = create(c, request(sharedWallet, UUID.randomUUID(), 2, null)); - assertThat(independent.paymentInstrumentId()).isEqualTo(original.paymentInstrumentId()); - var independentHold = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", - independent.requestId())) - .intoMap(); - var walletHistory = - c.setup() - .fetch( - "SELECT * FROM account_payment_instrument_observations WHERE instrument_uuid = ? ORDER BY row_version", - original.paymentInstrumentId()) - .intoMaps(); - - // Controlled provider absence is the cleanup evidence, not a fresh provisioning claim or a - // rewrite of wallet currentness. The original reservation still records observed version 1. - UUID terminalResolution = controlledTerminalCleanup(c, original); - var releasedHold = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", - original.requestId())) - .intoMap(); - assertThat(releasedHold.get("instrument_version")) - .isEqualTo(original.reservedInstrumentVersion()); - assertThat(releasedHold.get("terminal_resolution_id")).isEqualTo(terminalResolution); - assertThat(releasedHold.get("released_at")).isNotNull(); - var terminalReceipt = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ?", - terminalResolution)) - .intoMap(); - assertThat(controlledTerminalCleanup(c, original)).isEqualTo(terminalResolution); - assertThat(create(c, originalRequest)).isEqualTo(original); - - // An old request/subscription tuple or the originally observed version cannot select the - // independent version-2 reservation. Nor may a stale caller rewrite its immutable identity. - c.tx() - .executeWithoutResult( - s -> { - assertThat( - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " - + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", - terminalResolution, - independent.requestId(), - independent.subscriptionId(), - original.paymentInstrumentId(), - original.reservedInstrumentVersion())) - .isZero(); - assertThat( - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " - + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", - terminalResolution, - original.requestId(), - independent.subscriptionId(), - original.paymentInstrumentId(), - independent.reservedInstrumentVersion())) - .isZero(); - }); - for (String assignment : - List.of( - "request_id = '" + original.requestId() + "'::uuid", - "subscription_id = '" + original.subscriptionId() + "'::uuid", - "instrument_version = " + original.reservedInstrumentVersion())) { - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription_instrument_reservations SET " - + assignment - + ", terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ?", - terminalResolution, - independent.requestId())); - } - rejectSql( - "23505", - () -> - c.tx() - .executeWithoutResult( - s -> { - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ?", - terminalResolution, - independent.requestId()); - })); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", - independent.requestId())) - .intoMap()) - .isEqualTo(independentHold); - assertThat(c.repository().findCurrentByTenant(otherTenant.tenant()).orElseThrow().status()) - .isEqualTo("pending"); - assertThat( - Objects.requireNonNull( - c.tx() - .execute( - s -> c.repository().lockPendingForClaim(independent.requestId(), 1))) - .subscriptionId()) - .isEqualTo(independent.subscriptionId()); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", - original.requestId())) - .intoMap()) - .isEqualTo(releasedHold); - assertThat( - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ?", - terminalResolution)) - .intoMap()) - .isEqualTo(terminalReceipt); - assertThat(instruments.findByOwner(c.account(), original.paymentInstrumentId())) - .contains(advancedWallet); - assertThat( - c.setup() - .fetch( - "SELECT * FROM account_payment_instrument_observations WHERE instrument_uuid = ? ORDER BY row_version", - original.paymentInstrumentId()) - .intoMaps()) - .isEqualTo(walletHistory); - } - - @Test - void - providerHistoryAndTerminalEvidenceAreSeparateImmutableAndUnknownIdsNeverChooseCurrentAuthority() { - Context c = context(); - Seed seed = seed(c); - var creation = create(c, request(seed, UUID.randomUUID(), 1, null)); - assertThat(c.repository().lookupProviderId("sub_unknown").disposition()) - .isEqualTo(MappingDisposition.UNRESOLVED); - assertThat(count(c, "subscription_provider_history")).isZero(); - controlledProviderHistory(c, creation, "sub_original"); - assertThat(c.repository().lookupProviderId("sub_original").disposition()) - .isEqualTo(MappingDisposition.HISTORY_ONLY); - assertThat( - c.repository() - .findCurrentByTenant(seed.tenant()) - .orElseThrow() - .providerSubscriptionId()) - .isNull(); - c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_original', row_version = row_version + 1 WHERE subscription_id = ?", - creation.subscriptionId())); - var mapped = c.repository().lookupProviderId("sub_original"); - assertThat(mapped.disposition()).isEqualTo(MappingDisposition.CURRENT_MAPPING); - assertThat(mapped.history().orElseThrow().providerOperationId()) - .isEqualTo(creation.subscriptionProvisioningRequestId()); - assertThat(mapped.terminalResolution()).isEmpty(); - assertThat(c.repository().lookupProviderId("sub_predecessorNotRecorded").disposition()) - .isEqualTo(MappingDisposition.UNRESOLVED); - rejectSql("23505", () -> controlledProviderHistory(c, creation, "sub_conflicting")); - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_guessed', row_version = row_version + 1 WHERE subscription_id = ?", - creation.subscriptionId())); - controlledTerminalCleanup(c, creation); - var terminal = c.repository().lookupProviderId("sub_original"); - assertThat(terminal.disposition()).isEqualTo(MappingDisposition.TERMINAL_HISTORY); - assertThat(terminal.terminalResolution().orElseThrow().cleanupProviderIdentity()) - .isEqualTo(creation.cleanupProviderIdentity()); - var canceled = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); - create( - c, - request( - seed, - UUID.randomUUID(), - 1, - new ReplacementFence(creation.subscriptionId(), canceled.rowVersion()))); - var current = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); - assertThat(current.providerSubscriptionId()).isNull(); - assertThat( - c.repository() - .lookupProviderId("sub_original") - .history() - .orElseThrow() - .subscriptionId()) - .isEqualTo(creation.subscriptionId()); - assertThat(c.repository().findCurrentByTenant(seed.tenant())).contains(current); - for (String table : - List.of( - "subscription_provider_history", - "subscription_provider_terminal_resolutions", - "subscription_current_observations")) { - rejectSql("23514", () -> c.setup().execute("DELETE FROM " + table)); - rejectSql("23514", () -> c.setup().execute("TRUNCATE " + table + " CASCADE")); - } - rejectSql( - "23514", () -> c.setup().execute("UPDATE subscription_provider_history SET role = role")); - rejectSql( - "23514", - () -> - c.setup() - .execute( - "UPDATE subscription_provider_terminal_resolutions SET outcome = outcome")); - rejectSql( - "23503", - () -> c.setup().execute("DELETE FROM accounts WHERE account_uuid = ?", c.account())); - } - - private static void advanceBeforeCreate( - Context c, AccountSubscriptionCreateRequest request, Runnable controlledAdvance) - throws Exception { - CountDownLatch advanced = new CountDownLatch(1); - CountDownLatch contenderStarted = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - var holderPid = new AtomicInteger(); - var contenderPid = new AtomicInteger(); - var executor = Executors.newFixedThreadPool(2); - try { - var holder = - executor.submit( - () -> - c.tx() - .executeWithoutResult( - s -> { - holderPid.set( - Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - c.dsl() - .fetchOne( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", - c.account()); - controlledAdvance.run(); - advanced.countDown(); - await(release); - })); - if (!advanced.await(5, TimeUnit.SECONDS)) { - // Expose a failed owner transaction instead of masking it as a coordination timeout. - holder.get(1, TimeUnit.SECONDS); - throw new AssertionError("Controlled owner advance did not reach its lock boundary"); - } - var contender = - executor.submit( - () -> { - // Classify rejections only after the original create transaction has rolled back. - try { - c.tx() - .executeWithoutResult( - s -> { - contenderPid.set( - Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - contenderStarted.countDown(); - c.repository().retainPending(request); - }); - return "APPLIED"; - } catch (ConflictException conflict) { - return "CONFLICT"; - } catch (FenceRejectedException stale) { - return "FENCED"; - } - }); - assertThat(contenderStarted.await(5, TimeUnit.SECONDS)).isTrue(); - awaitBlocked(c, contenderPid.get(), holderPid.get()); - release.countDown(); - holder.get(15, TimeUnit.SECONDS); - assertThat(contender.get(15, TimeUnit.SECONDS)).isEqualTo("FENCED"); - } finally { - release.countDown(); - executor.shutdownNow(); - } - } - - private static void awaitBlocked(Context c, int waitingPid, int blockerPid) { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (System.nanoTime() < deadline) { - var observed = - Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blockerPid, waitingPid), - "Exact PostgreSQL blocking identity readback required"); - if (Boolean.TRUE.equals(observed.get("blocked", Boolean.class))) { - return; - } - Thread.onSpinWait(); - } - throw new IllegalStateException( - "Subscription create did not block on the controlled Account owner transaction"); - } - - /** Controlled qualified-result shape only; no Stripe or lifecycle producer is claimed. */ - private static void controlledProviderHistory( - Context c, AccountSubscriptionCreationRecord creation, String providerId) { - c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "INSERT INTO subscription_provider_history " - + "(provider_subscription_id,subscription_id,operation_kind,request_id,provider_operation_id,role,effective_at,evidence_digest) " - + "VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", - providerId, - creation.subscriptionId(), - creation.requestId(), - creation.subscriptionProvisioningRequestId(), - BOUNDARY, - DIGEST)); - } - - /** - * Controlled SQL cleanup tuple; does not prove provider verification or a lifecycle outbox - * bridge. - */ - private static UUID controlledTerminalCleanup( - Context c, AccountSubscriptionCreationRecord creation) { - return Objects.requireNonNull( - c.tx() - .execute( - s -> { - // Cleanup is not a new provisioning claim. Lock the same sources without - // requiring - // the globally shared wallet to retain the original observed - // version/availability. - new AccountPaymentInstrumentRepository(c.dsl()) - .findByOwnerForUpdate( - creation.owner().accountUuid(), creation.paymentInstrumentId()) - .orElseThrow(); - c.dsl() - .fetchOne( - "SELECT * FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", - creation.tenantId()); - var current = - Objects.requireNonNull( - c.dsl() - .fetchOne( - "SELECT * FROM subscription WHERE subscription_id = ? AND tenant_id = ? AND creation_request_id = ? FOR UPDATE", - creation.subscriptionId(), - creation.tenantId(), - creation.requestId())); - var hold = - Objects.requireNonNull( - c.dsl() - .fetchOne( - "SELECT * FROM subscription_instrument_reservations WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? FOR UPDATE", - creation.requestId(), - creation.subscriptionId(), - creation.paymentInstrumentId(), - creation.reservedInstrumentVersion())); - if (hold.get("released_at") != null) { - UUID retainedResolution = hold.get("terminal_resolution_id", UUID.class); - assertThat(current.get("status", String.class)).isEqualTo("canceled"); - assertThat(current.get("terminal_resolution_id", UUID.class)) - .isEqualTo(retainedResolution); - var receipt = - Objects.requireNonNull( - c.dsl() - .fetchOne( - "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ? AND request_id = ? AND subscription_id = ? AND cleanup_provider_identity = ?", - retainedResolution, - creation.requestId(), - creation.subscriptionId(), - creation.cleanupProviderIdentity())); - assertThat(receipt.get("provider_subscription_id", String.class)) - .isEqualTo(current.get("provider_subscription_id", String.class)); - return retainedResolution; - } - UUID resolution = UUID.randomUUID(); - c.dsl() - .execute( - "INSERT INTO subscription_provider_terminal_resolutions " - + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,provider_subscription_id,outcome,effective_at,evidence_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?)", - resolution, - creation.requestId(), - creation.subscriptionId(), - creation.cleanupProviderIdentity(), - current.get("provider_subscription_id", String.class), - current.get("provider_subscription_id") == null - ? "PROVIDER_ABSENT" - : "CANCELED", - BOUNDARY, - DIGEST); - assertThat( - c.dsl() - .execute( - "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ? AND creation_request_id = ? AND row_version = ? AND status = 'pending'", - resolution, - creation.subscriptionId(), - creation.requestId(), - current.get("row_version", Long.class))) - .isOne(); - assertThat( - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", - resolution, - creation.requestId(), - creation.subscriptionId(), - creation.paymentInstrumentId(), - creation.reservedInstrumentVersion())) - .isOne(); - return resolution; - })); - } - - private static void advanceWallet(Context c, UUID instrument, UUID changeRequest) { - c.dsl() - .execute( - "UPDATE payment_instrument SET row_version = row_version + 1, change_request_id = ?, evidence_digest = ? WHERE instrument_uuid = ?", - changeRequest, - DIGEST, - instrument); - } - - private static void insertBareOperation( - Context c, - AccountSubscriptionCreateRequest request, - Seed seed, - UUID createKey, - UUID cleanupKey) { - var quote = configuredPlans().resolve(request.planCode()); - insertBareOperationWithQuote( - c, request, seed, createKey, cleanupKey, quote, quote.payload(), quote.digest()); - } - - private static void insertBareOperationWithQuote( - Context c, - AccountSubscriptionCreateRequest request, - Seed seed, - UUID createKey, - UUID cleanupKey, - AccountHostingPlanQuote quote, - byte[] quotePayload, - String quoteDigest) { - var encoded = - AccountSubscriptionCreateDigest.encode( - request.tenantId(), - request.owner().accountUuid(), - request.planCode(), - request.paymentInstrumentId()); - c.dsl() - .execute( - "INSERT INTO subscription_create_operations (request_id,subscription_id,tenant_id,account_uuid,owner_version,owner_generation,actor_account_uuid,authorization_operation_id,authorization_digest,plan_code,payment_instrument_id,reserved_instrument_version,customer_provisioning_request_id,provider_customer_id,subscription_provisioning_request_id,cleanup_provider_identity,request_payload,request_digest,plan_quote_payload,plan_quote_digest,provider_price_id,provider_quantity,max_active_sessions,max_concurrent_game_instances,max_storage_bytes) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - request.requestId(), - UUID.randomUUID(), - request.tenantId(), - request.owner().accountUuid(), - request.owner().version(), - request.owner().generation(), - c.account(), - request.producer().authorizationOperationId(), - request.producer().authorizationDigest(), - request.planCode(), - request.paymentInstrumentId(), - request.instrumentVersion(), - seed.instrument().customerProvisioningRequestId(), - seed.instrument().providerCustomerId(), - createKey, - cleanupKey, - encoded.payload(), - encoded.digest(), - quotePayload, - quoteDigest, - quote.providerPriceId(), - quote.providerQuantity(), - quote.maxActiveSessions(), - quote.maxConcurrentGameInstances(), - quote.maxStorageBytes()); - } - - private static AccountSubscriptionCreationRecord create( - Context c, AccountSubscriptionCreateRequest request) { - return Objects.requireNonNull(c.tx().execute(s -> c.repository().retainPending(request))); - } - - private static String attemptCreate(Context c, AccountSubscriptionCreateRequest request) { - try { - create(c, request); - return "APPLIED"; - } catch (ConflictException conflict) { - return "CONFLICT"; - } catch (FenceRejectedException stale) { - return "FENCED"; - } - } - - private static AccountSubscriptionCreateRequest request( - Seed seed, UUID request, long instrumentVersion, ReplacementFence replacement) { - return new AccountSubscriptionCreateRequest( - request, - seed.tenant(), - seed.owner(), - "basic-hosting", - seed.instrument().instrumentUuid(), - instrumentVersion, - producer(seed.owner().accountUuid()), - replacement); - } - - private static ProducerEvidence producer(UUID account) { - return new ProducerEvidence(account, UUID.randomUUID(), DIGEST); - } - - private static Seed seed(Context c) { - UUID tenant = UUID.randomUUID(); - UUID creationRequest = UUID.randomUUID(); - UUID creationOperation = UUID.randomUUID(); - long gameRow = GAME_ROWS.incrementAndGet(); - String key = "game-" + gameRow; - String requestDigest = - GameTenantCreationDigest.requestDigest( - "prod", creationRequest, key, "Controlled tenant", "Storage proof only"); - var creation = - new FreshTenantCreationEvidence( - 1, - "prod", - creationRequest, - creationOperation, - requestDigest, - tenant, - gameRow, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - "prod", - creationRequest, - creationOperation, - requestDigest, - tenant, - gameRow, - key, - "NEW_GAME_ROW")); - UUID authorityOperation = UUID.randomUUID(); - var creator = - new FreshTenantCreatorEvidence( - 1, - creation, - c.account(), - authorityOperation, - DIGEST, - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, c.account(), authorityOperation, DIGEST)); - c.tx() - .executeWithoutResult( - s -> - new FreshTenantIdentityAssociationRepository(c.dsl(), "prod") - .importVerified(creation)); - var ownerResult = - Objects.requireNonNull( - c.tx() - .execute( - s -> - new AccountInitialTenantBillingOwnerRepository(c.dsl()) - .establishInitial( - new AccountInitialTenantBillingOwnerRepository.InitialRequest( - UUID.randomUUID(), creator, UUID.randomUUID(), 1, true)))); - var customers = new AccountBillingCustomerRepository(c.dsl()); - var customer = - Objects.requireNonNull( - c.tx() - .execute( - s -> - customers.retainIntent( - c.account(), UUID.randomUUID(), UUID.randomUUID()))) - .customer(); - if (customer.state() != AccountBillingCustomerRecord.State.CONFIRMED) { - var pending = customer; - customer = - Objects.requireNonNull( - c.tx() - .execute( - s -> - customers.recordObservation( - c.account(), - pending.customerProvisioningRequestId(), - pending.rowVersion(), - UUID.randomUUID(), - AccountBillingCustomerRecord.Observation.CONFIRMED, - "cus_" + c.account().toString().replace("-", ""), - DIGEST))); - } - var confirmed = customer; - var instrument = - Objects.requireNonNull( - c.tx() - .execute( - s -> - new AccountPaymentInstrumentRepository(c.dsl()) - .retainAttachment( - new Attachment( - UUID.randomUUID(), - UUID.randomUUID(), - c.account(), - confirmed.customerProvisioningRequestId(), - confirmed.providerCustomerId(), - "pm_" + UUID.randomUUID().toString().replace("-", ""), - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new DisplayMetadata("visa", "4242", 12, 2030), - DIGEST)))); - return new Seed( - tenant, - new OwnerFence(c.account(), ownerResult.ownerVersion(), ownerResult.ownerGeneration()), - instrument); - } - - private static List race(Supplier left, Supplier right) throws Exception { - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch start = new CountDownLatch(1); - var executor = Executors.newFixedThreadPool(2); - try { - var first = - executor.submit( - () -> { - ready.countDown(); - await(start); - return left.get(); - }); - var second = - executor.submit( - () -> { - ready.countDown(); - await(start); - return right.get(); - }); - assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - return List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); - } finally { - start.countDown(); - executor.shutdownNow(); - } - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Storage proof barrier timed out"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Storage proof interrupted", interrupted); - } - } - - private static void rejectSql(String state, ThrowingCallable action) { - assertThatThrownBy(action) - .satisfies( - failure -> { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - assertThat(sql.getSQLState()).isEqualTo(state); - return; - } - } - throw new AssertionError("Expected PostgreSQL invariant refusal", failure); - }); - } - - private static long count(Context c, String table) { - return Objects.requireNonNull(c.setup().fetchOne("SELECT count(*) FROM " + table)) - .get(0, Long.class); - } - - private static String indexDefinition(Context c, String name) { - return Objects.requireNonNull( - c.setup() - .fetchOne( - "SELECT indexdef FROM pg_indexes WHERE schemaname = current_schema() AND indexname = ?", - name)) - .get(0, String.class); - } - - private static FluentConfiguration configuration(Context c) { - return Flyway.configure() - .dataSource(c.source()) - .schemas(c.schema()) - .defaultSchema(c.schema()) - .placeholders(Map.of("serviceSchema", c.schema())) - .locations("classpath:db/migration", "classpath:db/migration/saga"); - } - - private static Context context() { - Context c = predecessor(); - configuration(c).target("1029").load().migrate(); - return c; - } - - private static Context predecessor() { - String schema = "subscription_intent_" + UUID.randomUUID().toString().replace("-", ""); - var source = - new DriverManagerDataSource( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - source.setSchema(schema); - DSLContext setup = DSL.using(source, SQLDialect.POSTGRES); - DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); - var tx = new TransactionTemplate(new DataSourceTransactionManager(source)); - tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - tx.setTimeout(10); - var empty = - new Context( - source, - schema, - setup, - dsl, - tx, - new AccountSubscriptionIntentRepository(dsl, configuredPlans()), - null); - configuration(empty).target("1026").load().migrate(); - var account = - Objects.requireNonNull( - setup.fetchOne( - "INSERT INTO accounts(username,email,password_hash) VALUES ('subscription-owner','owner@example.test','hash') RETURNING id, account_uuid")); - setup.execute( - "INSERT INTO subscription(id,account_id,plan_id,status,started_at,ended_at,tenant_id,entitlement_version,tenant_authority_generation) VALUES " - + "(91,?,'unqualified-active','active','2025-01-02 03:04:05.123456',NULL,7,19,?)," - + "(92,?,'retained-canceled','canceled',NULL,'2025-02-03 04:05:06.654321',7,21,?)", - account.get("id", Long.class), - UUID.randomUUID(), - account.get("id", Long.class), - UUID.randomUUID()); - return new Context( - source, - schema, - setup, - dsl, - tx, - empty.repository(), - account.get("account_uuid", UUID.class)); - } - - /** Controlled configuration only; not an installed live catalog or production price selection. */ - private static AccountHostingPlanCatalog configuredPlans() { - return new AccountHostingPlanCatalog( - List.of( - new AccountHostingPlanCatalog.ConfiguredPlan( - "basic-hosting", "price_controlledInitial", "1", "100", "2", "1048576"))); - } - - private record Seed(UUID tenant, OwnerFence owner, AccountPaymentInstrumentRecord instrument) {} - - private record Context( - DriverManagerDataSource source, - String schema, - DSLContext setup, - DSLContext dsl, - TransactionTemplate tx, - AccountSubscriptionIntentRepository repository, - UUID account) {} -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java deleted file mode 100644 index 965acade65..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java +++ /dev/null @@ -1,350 +0,0 @@ -package integration.net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.sql.SQLException; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; -import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Actual Flyway/PostgreSQL source selection over committed demo and hosting owners. Enrollment and - * Stripe transport are controlled fixture inputs. No triggers are bypassed and no clock is changed; - * this does not qualify authenticated producers, live Stripe, public registration or admission. - */ -@Testcontainers(disabledWithoutDocker = true) -class AccountTenantAuthoritySourceSelectionPostgresIntegrationTest { - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void retainedPendingSubscriptionWithoutCommittedTenantSourceIsUnavailable() { - Context c = context(); - var f = c.fixture(); - assertThat(f.intents().findCurrentByTenant(f.tenantId())).isPresent(); - assertThatThrownBy(c::select).hasMessageContaining("Current tenant source is absent"); - assertThat(f.transport().reads()).isZero(); - assertThat( - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT count(*) FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", - f.tenantId())) - .get(0, Long.class)) - .isZero(); - } - - @Test - void demoSelectionUsesExactCommittedBindingWhilePaidConfigurationIsRetained() { - Context c = context(); - var f = c.fixture(); - DemoTenantEntitlementSnapshot first = c.provisionDemo(null, true); - SourceSelection selected = c.select(); - assertThat(selected.kind()).isEqualTo(SourceKind.NON_PAID_DEMO); - assertThat(selected.checkpoint().tenantBillingEventId()).isEqualTo(first.eventId()); - assertThat(selected.checkpoint().tenantBillingEventDigest()).isEqualTo(first.eventDigest()); - assertThat(selected.checkpoint().eventId()).isEqualTo(first.tenantAuthorityEventId()); - assertThat(selected.checkpoint().eventDigest()).isEqualTo(first.tenantAuthorityEventDigest()); - assertCurrentCheckpoint(c, selected); - assertThat(f.intents().findCurrentByTenant(f.tenantId()).orElseThrow().status()) - .isEqualTo("pending"); - assertThat(f.transport().reads()).isZero(); - - // A genuine owner mutation changes the source; the earlier selected identity cannot follow it. - DemoTenantEntitlementSnapshot second = c.provisionDemo(first, false); - SourceSelection current = c.select(); - assertThat(current.kind()).isEqualTo(SourceKind.NON_PAID_DEMO); - assertThat(selected.matches(current.checkpoint())).isFalse(); - assertThat(current.checkpoint().tenantBillingSequence()) - .isEqualTo(first.tenantBillingSequence() + 1) - .isEqualTo(second.tenantBillingSequence()); - assertThatThrownBy(() -> f.transaction().execute(status -> c.demos().revalidate(first))) - .hasMessageContaining("changed after"); - assertThat( - f.transaction() - .execute(status -> c.demos().readCurrent(f.tenantId())) - .allowPublicJoin()) - .isFalse(); - assertCurrentCheckpoint(c, current); - assertThat(f.transport().reads()).isZero(); - } - - @Test - void paidCommitReplacesHeadWithoutDeletingOrSelectingTheRetainedDemoFamily() { - Context c = context(); - var f = c.fixture(); - DemoTenantEntitlementSnapshot demo = c.provisionDemo(null, true); - SourceSelection oldSelection = c.select(); - var retainedDemoRow = - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT row_to_json(e)::text FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", - f.tenantId())); - assertThat(retainedDemoRow).isNotNull(); - String retainedDemo = retainedDemoRow.get(0, String.class); - var retainedDemoEventRow = - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", - f.tenantId(), - demo.tenantBillingSequence())); - assertThat(retainedDemoEventRow).isNotNull(); - byte[] retainedDemoEvent = retainedDemoEventRow.get(0, byte[].class); - - UUID paidRequest = c.activatePaid(); - int providerReads = f.transport().reads(); - SourceSelection paid = c.select(); - assertThat(paid.kind()).isEqualTo(SourceKind.PAID_HOSTING); - assertThat(paid.checkpoint().requestId()).isEqualTo(paidRequest); - assertThat(paid.checkpoint().tenantBillingSequence()) - .isEqualTo(demo.tenantBillingSequence() + 1); - assertThat(oldSelection.matches(paid.checkpoint())).isFalse(); - assertCurrentCheckpoint(c, paid); - // Source selection is only routing data; it does not make its own provider observation. - assertThat(f.transport().reads()).isEqualTo(providerReads); - var actualReceipt = f.service().readCurrent(f.tenantId()); - assertThat(paid.matches(actualReceipt.tenantAuthorityEvent())).isTrue(); - assertThat(paid.checkpoint().tenantBillingEventId()).isEqualTo(actualReceipt.billingEventId()); - assertThat(paid.checkpoint().tenantBillingEventDigest()) - .isEqualTo(actualReceipt.billingEventDigest()); - assertThat(f.transport().reads()).isEqualTo(providerReads + 1); - - assertThat( - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT row_to_json(e)::text FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", - f.tenantId())) - .get(0, String.class)) - .isEqualTo(retainedDemo); - assertThat( - Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", - f.tenantId(), - demo.tenantBillingSequence())) - .get(0, byte[].class)) - .isEqualTo(retainedDemoEvent); - assertThat(f.intents().findCurrentByTenant(f.tenantId()).orElseThrow().status()) - .isEqualTo("active"); - assertThatThrownBy(() -> f.transaction().execute(status -> c.demos().readCurrent(f.tenantId()))) - .hasMessageContaining("stale against Account's shared tenant authority generation"); - assertThat(c.select().kind()).isEqualTo(SourceKind.PAID_HOSTING); - } - - @Test - void immutableBillingReceiptAndHeadGuardsRejectMalformedOrMismatchingReplacement() { - Context c = context(); - var f = c.fixture(); - c.activatePaid(); - SourceSelection original = c.select(); - - // These corruptions cannot become committed source states under the production guards. - assertSqlState23514( - () -> - f.dsl() - .execute( - "UPDATE account_tenant_entitlement_outbox_events SET payload = ? WHERE tenant_uuid = ?", - "{\"schemaVersion\":\"unknown-source/v1\"}" - .getBytes(java.nio.charset.StandardCharsets.UTF_8), - f.tenantId())); - assertSqlState23514( - () -> - f.dsl() - .execute( - "UPDATE account_tenant_authority_source_records SET tenant_billing_event_digest = ? WHERE tenant_uuid = ?", - "sha256:" + "f".repeat(64), - f.tenantId())); - assertSqlState23514( - () -> - f.dsl() - .execute( - "UPDATE subscription_lifecycle_receipts SET receipt_payload = ? WHERE tenant_id = ?", - new byte[] {'{', '}'}, - f.tenantId())); - - SourceSelection unchanged = c.select(); - assertThat(unchanged.kind()).isEqualTo(SourceKind.PAID_HOSTING); - assertThat(original.matches(unchanged.checkpoint())).isTrue(); - assertCurrentCheckpoint(c, unchanged); - } - - private static void assertCurrentCheckpoint(Context c, SourceSelection selected) { - var f = c.fixture(); - var head = - f.dsl() - .fetchOne( - "SELECT * FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", - f.tenantId()); - assertThat(head).isNotNull(); - assertThat(selected.checkpoint().eventId().toString()) - .isEqualTo(head.get("last_event_id", String.class)); - assertThat(selected.checkpoint().eventDigest()) - .isEqualTo(head.get("last_event_digest", String.class)); - assertThat(selected.checkpoint().tenantAuthorityGeneration()) - .isEqualTo(head.get("current_generation", Long.class)); - assertThat(selected.checkpoint().tenantAuthoritySourceVersion()) - .isEqualTo(head.get("current_source_version", Long.class)); - assertThat(selected.checkpoint().requestId()) - .isEqualTo(head.get("last_request_id", UUID.class)); - assertThat(selected.checkpoint().tenantBillingSequence()) - .isEqualTo(head.get("tenant_billing_sequence", Long.class)); - var checkpoint = - Objects.requireNonNull( - f.transaction() - .execute( - status -> - new AccountAuthorityOutboxRepository(f.dsl()) - .readCheckpoint(TenantAuthorityEventV1Codec.streamKey(f.tenantId())) - .orElseThrow())); - assertThat(selected.checkpoint().outboxSequence()).isEqualTo(checkpoint.outboxSequence()); - assertThat(selected.checkpoint().eventId().toString()).isEqualTo(checkpoint.sourceEventId()); - assertThat(selected.checkpoint().eventDigest()).isEqualTo(checkpoint.sourceEventDigest()); - var billing = - f.dsl() - .fetchOne( - "SELECT e.event_id, e.event_digest, s.last_sequence FROM account_tenant_entitlement_outbox_events e " - + "JOIN account_tenant_entitlement_outbox_streams s USING (tenant_uuid) " - + "WHERE e.tenant_uuid = ? AND e.tenant_billing_sequence = ?", - f.tenantId(), - selected.checkpoint().tenantBillingSequence()); - assertThat(billing).isNotNull(); - assertThat(selected.checkpoint().tenantBillingSequence()) - .isEqualTo(billing.get("last_sequence", Long.class)); - assertThat(selected.checkpoint().tenantBillingEventId()) - .isEqualTo(billing.get("event_id", UUID.class)); - assertThat(selected.checkpoint().tenantBillingEventDigest()) - .isEqualTo(billing.get("event_digest", String.class)); - } - - private static void assertSqlState23514(Runnable operation) { - RuntimeException failure = assertThrows(RuntimeException.class, operation::run); - Throwable current = failure; - while (current != null) { - if (current instanceof SQLException sql) { - assertThat(sql.getSQLState()).isEqualTo("23514"); - return; - } - current = current.getCause(); - } - throw new AssertionError("Expected PostgreSQL guard refusal", failure); - } - - private static Context context() { - String schema = "source_selection_" + UUID.randomUUID().toString().replace("-", ""); - var source = - new DriverManagerDataSource( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - source.setSchema(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration", "classpath:db/migration/saga") - .load() - .migrate(); - var f = CanonicalHostingSubscriptionTestFixture.create(source); - var identities = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); - var generations = new AccountAuthorityGenerationRepository(f.dsl()); - var billing = new AccountTenantEntitlementOutboxRepository(f.dsl()); - var events = - new AccountTenantAuthorityEventRepository( - f.dsl(), - new AccountAuthorityOutboxRepository(f.dsl()), - billing, - identities, - generations); - var demos = - new AccountDemoTenantEntitlementRepository( - f.dsl(), identities, generations, billing, events); - return new Context(f, events, demos); - } - - private record Context( - CanonicalHostingSubscriptionTestFixture.Fixture fixture, - AccountTenantAuthorityEventRepository events, - AccountDemoTenantEntitlementRepository demos) { - private SourceSelection select() { - return Objects.requireNonNull( - fixture - .transaction() - .execute(status -> events.readCurrentSourceSelection(fixture.tenantId()))); - } - - private DemoTenantEntitlementSnapshot provisionDemo( - DemoTenantEntitlementSnapshot prior, boolean publicJoin) { - return Objects.requireNonNull( - fixture - .transaction() - .execute( - status -> { - var source = - new FreshTenantIdentityAssociationRepository(fixture.dsl(), "prod") - .read(fixture.tenantId()) - .orElseThrow(); - return demos.provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - fixture.tenantId(), - source.creationRequestId(), - source.requestDigest(), - prior == null ? null : prior.entitlementVersion(), - prior == null ? null : prior.tenantAuthorityGeneration(), - prior == null ? null : prior.tenantAuthoritySourceVersion(), - true, - publicJoin, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 1, 1024)), - source); - })); - } - - private UUID activatePaid() { - var claim = - fixture - .service() - .claimProvisioning(fixture.creation().requestId(), 1L, UUID.randomUUID()) - .claim(); - UUID requestId = UUID.randomUUID(); - assertThat( - fixture - .service() - .reconcile( - requestId, - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - return requestId; - } - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index 69f0cec8df..d72151f370 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -10,14 +10,10 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; -import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; -import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -31,8 +27,6 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; @@ -42,11 +36,7 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; -import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; @@ -310,587 +300,6 @@ void terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether() { assertThat(operation.terminalProof()).isNull(); } - @Test - void activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays() { - Fixture fixture = newFixture(); - var original = fixture.commitFirstJoin(); - String nextRequest = fixture.prepareAnotherJoin(); - var result = fixture.commitExistingJoin(nextRequest); - var replay = fixture.commitExistingJoin(nextRequest); - - assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); - assertThat(result.membershipId()).isEqualTo(original.membershipId()); - assertThat(result.membershipVersion()).isEqualTo(2L); - assertThat(result.membershipAuthorityGeneration()).isEqualTo(1L); - assertThat(result.terminalProof().eventSequence()).isEqualTo(1L); - assertThat(result.terminalProof().auditEventId()).isNull(); - assertThat(replay).isEqualTo(result); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(1L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.dsl.execute( - "UPDATE account_join_operations SET outcome_membership_version = 3 WHERE request_id = ?", - nextRequest))) - .isInstanceOf(RuntimeException.class) - .rootCause() - .isInstanceOfSatisfying( - java.sql.SQLException.class, - failure -> { - assertThat(failure.getSQLState()).isEqualTo("23514"); - assertThat(failure.getMessage()) - .contains("Terminal canonical JOIN receipt is immutable"); - }); - } - - @Test - void nullCommittedOutcomeIsRejectedByTerminalReceiptShapeGuard() { - Fixture fixture = newFixture(); - fixture.commitFirstJoin(); - String nextRequest = fixture.prepareAnotherJoin(); - - // Retain a valid current membership witness but omit only the required committed outcome. - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.dsl.execute( - """ - UPDATE account_join_operations pending - SET status = 'COMMITTED', outcome = NULL, - last_attempt_authority_availability = 'AVAILABLE', - membership_id = original.membership_id, - outcome_membership_version = original.outcome_membership_version, - outcome_membership_authority_generation = original.outcome_membership_authority_generation, - membership_authority_outbox_stream_key = original.membership_authority_outbox_stream_key, - membership_authority_outbox_sequence = original.membership_authority_outbox_sequence, - membership_authority_event_id = original.membership_authority_event_id, - membership_authority_event_digest = original.membership_authority_event_digest - FROM account_join_operations original - WHERE pending.request_id = ? AND original.request_id = ? - """, - nextRequest, - fixture.requestId))) - .isInstanceOf(RuntimeException.class) - .rootCause() - .isInstanceOfSatisfying( - java.sql.SQLException.class, - failure -> { - assertThat(failure.getSQLState()).isEqualTo("23514"); - assertThat(failure.getMessage()) - .contains("Canonical JOIN terminal receipt is incomplete or noncommitting"); - }); - - var committed = fixture.commitExistingJoin(nextRequest); - assertThat(committed.status()).isEqualTo("COMMITTED"); - assertThat(committed.outcome()).isEqualTo("ALREADY_ACTIVE"); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - } - - @Test - void closingEnrollmentPreservesAnActiveMembersEventFreeJoinSnapshot() { - Fixture fixture = newFixture(); - fixture.commitFirstJoin(); - fixture.inTransaction( - () -> { - var current = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); - fixture.demoEntitlements.provision( - fixture.entitlementRequest(UUID.randomUUID(), current, false), - fixture.tenantEvidence); - return null; - }); - String requestId = fixture.prepareAnotherJoin(); - var result = fixture.commitExistingJoin(requestId); - assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); - assertThat(result.allowPublicJoin()).isFalse(); - assertThat(result.membershipVersion()).isEqualTo(2L); - assertThat(result.membershipAuthorityGeneration()).isEqualTo(1L); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(1L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - } - - @Test - void activeNonAdmittingSnapshotWithoutPlayerRoleRemainsSuccessfulAndUnchanged() { - Fixture fixture = newFixture(); - fixture.commitFirstJoin(); - fixture.seedControlledMembershipSnapshot("ACTIVE", java.util.List.of()); - BrowserFacade browser = fixture.browserFacade(); - var selected = - browser.service().listBootstrapRealms(browser.bootstrapToken(), "world").getFirst(); - var request = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - selected.connectScopeId(), UUID.randomUUID().toString()); - var result = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - assertThat(result.success()).isTrue(); - assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); - assertThat(result.gameplayAdmissionAllowed()).isFalse(); - assertThat(result.membershipVersion()).isEqualTo(3L); - assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); - assertThat(replay.gameplayAdmissionAllowed()).isFalse(); - assertThat(replay.replayed()).isTrue(); - var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); - var roles = - fixture.inTransaction( - () -> - fixture - .roles - .findForCanonicalUpdate( - fixture.account.getAccountUuid(), - fixture.tenantUuid, - fixture.provenance, - member.getId(), - 3L) - .orElseThrow()); - assertThat(roles.roles()).isEmpty(); - assertThat(member.isGameplayAdmissionAllowed()).isFalse(); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(2L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - } - - @Test - void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { - Fixture fixture = newFixture(); - var checkpoint = fixture.writeAndPublish(); - assertThatThrownBy(() -> fixture.commitExistingJoin(fixture.requestId)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("precommitted transition"); - var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); - var proof = - new AccountJoinOperationRepository.CanonicalJoinTerminalProof( - checkpoint.outboxStreamKey(), - checkpoint.outboxSequence(), - checkpoint.sourceEventId(), - checkpoint.sourceEventDigest(), - null, - null, - null, - 1L, - member.getId(), - member.getMembershipVersion(), - member.getMembershipAuthorityGeneration()); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.operations.commitCanonicalJoin( - fixture.requestId, - fixture.scope, - fixture.callerBinding, - "ALREADY_ACTIVE", - proof))) - .isInstanceOf(RuntimeException.class) - .rootCause() - .isInstanceOfSatisfying( - java.sql.SQLException.class, - failure -> { - assertThat(failure.getSQLState()).isEqualTo("23514"); - assertThat(failure.getMessage()) - .contains( - "Canonical JOIN terminal receipt does not match committed owner evidence"); - }); - assertThat(fixture.countAll("account_audit_outbox")).isZero(); - assertThat( - fixture - .inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) - .orElseThrow()) - .status()) - .isEqualTo("PENDING"); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void committedJoinReplaysStoredEvidenceAfterLaterMembershipChanges(boolean alreadyActive) { - Fixture fixture = newFixture(); - fixture.commitFirstJoin(); - String originalRequest = alreadyActive ? fixture.prepareAnotherJoin() : fixture.requestId; - var committed = fixture.commitExistingJoin(originalRequest); - assertThat(committed.outcome()).isEqualTo(alreadyActive ? "ALREADY_ACTIVE" : "JOINED"); - - // Controlled historical owner input, not proof of a production leave API. - fixture.seedControlledInactiveOwnerSnapshot(); - var tables = - java.util.List.of( - "account_join_operations", - "account_tenant_membership", - "account_tenant_membership_role_snapshots", - "account_membership_pair_authority", - "account_authority_outbox_events", - "account_authority_outbox_streams", - "account_audit_outbox"); - java.util.function.Supplier storedRows = - () -> - tables.stream() - .map( - table -> - fixture - .dsl - .fetch( - "SELECT xmin::text AS row_version, to_jsonb(t)::text AS row_data FROM " - + table - + " t ORDER BY to_jsonb(t)::text") - .intoMaps()) - .toList(); - var inactiveRows = storedRows.get(); - assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); - assertThat(storedRows.get()).isEqualTo(inactiveRows); - - // A real subsequent JOIN owner operation advances the event and restores membership. - var restored = fixture.commitExistingJoin(fixture.prepareAnotherJoin()); - assertThat(restored.terminalProof().eventSequence()).isEqualTo(3L); - assertThat(restored.membershipVersion()).isEqualTo(4L); - var restoredRows = storedRows.get(); - assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.terminalCoordinator.commitCanonicalJoin( - fixture.scope, originalRequest, "different-caller", null, null, null))) - .isInstanceOf(CanonicalJoinOperationConflictException.class); - assertThat(storedRows.get()).isEqualTo(restoredRows); - } - - @Test - void inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration() { - Fixture fixture = newFixture(); - var first = fixture.commitFirstJoin(); - fixture.seedControlledInactiveOwnerSnapshot(); - String restoreRequest = fixture.prepareAnotherJoin(); - var result = fixture.commitExistingJoin(restoreRequest); - var replay = fixture.commitExistingJoin(restoreRequest); - - assertThat(result.outcome()).isEqualTo("JOINED"); - assertThat(result.membershipId()).isEqualTo(first.membershipId()); - assertThat(result.membershipVersion()).isEqualTo(4L); - assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); - assertThat(result.terminalProof().eventSequence()).isEqualTo(3L); - assertThat(result.terminalProof().auditEventId()) - .isNotNull() - .isNotEqualTo(first.auditEventId()); - assertThat(replay).isEqualTo(result); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(3L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(2L); - var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); - assertThat(member.getLifecycleState()).isEqualTo("ACTIVE"); - assertThat(member.isGameplayAdmissionAllowed()).isTrue(); - } - - @Test - void restoreTerminalFailureRollsBackMemberRolesPairEventAndAudit() { - Fixture fixture = newFixture(); - fixture.commitFirstJoin(); - fixture.seedControlledInactiveOwnerSnapshot(); - String restoreRequest = fixture.prepareAnotherJoin(); - fixture.dsl.execute( - "CREATE FUNCTION fail_restore_terminal() RETURNS trigger LANGUAGE plpgsql AS $$ " - + "BEGIN IF NEW.status = 'COMMITTED' THEN RAISE EXCEPTION 'restore terminal failure'; " - + "END IF; RETURN NEW; END $$"); - fixture.dsl.execute( - "CREATE TRIGGER fail_restore_terminal BEFORE UPDATE ON account_join_operations " - + "FOR EACH ROW EXECUTE FUNCTION fail_restore_terminal()"); - - assertThatThrownBy(() -> fixture.commitExistingJoin(restoreRequest)) - .isInstanceOf(RuntimeException.class) - .hasMessageContaining("restore terminal failure"); - var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); - assertThat(member.getLifecycleState()).isEqualTo("INACTIVE"); - assertThat(member.getMembershipVersion()).isEqualTo(3L); - assertThat(member.getMembershipAuthorityGeneration()).isEqualTo(2L); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(2L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - var operation = - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(restoreRequest) - .orElseThrow()); - assertThat(operation.status()).isEqualTo("PENDING"); - assertThat(operation.terminalProof()).isNull(); - } - - @Test - void browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommittedReceipt() { - Fixture fixture = newFixture(); - BrowserFacade browser = fixture.browserFacade(); - var realms = browser.service().listBootstrapRealms(browser.bootstrapToken(), "world"); - var selected = realms.getFirst(); - String requestId = UUID.randomUUID().toString(); - var request = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - selected.connectScopeId(), requestId); - - var first = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - - assertThat(first.success()).isTrue(); - assertThat(first.outcomeCode()).isEqualTo("JOINED"); - assertThat(first.accountId()).isEqualTo(fixture.account.getAccountUuid().toString()); - assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); - assertThat(first.membershipVersion()).isEqualTo(2L); - assertThat(first.membershipAuthorityGeneration()).isEqualTo(1L); - assertThat(first.gameplayAdmissionAllowed()).isTrue(); - assertThat(first.replayed()).isFalse(); - assertThat(replay.success()).isTrue(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.membershipId()).isEqualTo(first.membershipId()); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(1L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - var stored = - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow()); - assertThat(stored.status()).isEqualTo("COMMITTED"); - assertThat(stored.operationRepresentationVersion()).isEqualTo(2); - assertThat(stored.scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource( - strings = {"COMMITTED", "FAILED_UNBOUND", "FAILED_BOUND"}) - void browserFacadeReplaysOperationFinishedAfterPreparation(String terminalState) { - Fixture fixture = newFixture(); - BrowserFacade browser = fixture.browserFacade(); - var selected = - browser.service().listBootstrapRealms(browser.bootstrapToken(), "world").getFirst(); - String requestId = UUID.randomUUID().toString(); - var request = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - selected.connectScopeId(), requestId); - var callerReads = new java.util.concurrent.atomic.AtomicInteger(); - var retained = - new java.util.concurrent.atomic.AtomicReference< - AccountJoinOperationRepository.CanonicalJoinOperationEvidence>(); - org.mockito.Mockito.when( - browser - .sessions() - .isAccountSessionActive(fixture.account.getId(), browser.bootstrapToken())) - .thenAnswer( - invocation -> { - // The second caller read occurs outside SQL, after preparation and immediately before - // the final transaction. Finish another exact attempt in this deterministic gap. - if (callerReads.incrementAndGet() == 2) { - if ("COMMITTED".equals(terminalState)) { - var first = - browser.service().joinPublicProduction(browser.bootstrapToken(), request); - assertThat(first.success()).isTrue(); - assertThat(first.replayed()).isFalse(); - } else { - fixture.inTransaction( - () -> { - fixture.operations.lockAccount(fixture.account.getId()); - var scope = - fixture - .connectScopes - .findCanonical(selected.connectScopeId()) - .orElseThrow(); - var pending = - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - assertThat(pending.status()).isEqualTo("PENDING"); - if ("FAILED_BOUND".equals(terminalState)) { - var policy = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); - fixture.operations.bindCanonicalPolicyEvidence( - requestId, - scope, - pending.callerBinding(), - policy.allowPublicJoin(), - policy.entitlementVersion()); - } - fixture.operations.finishCanonicalFailure( - requestId, scope, pending.callerBinding(), "CONNECT_SCOPE_MISMATCH"); - return null; - }); - } - retained.set( - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow())); - } - return true; - }); - - var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - - assertThat(retained.get()).isNotNull(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.success()).isEqualTo("COMMITTED".equals(terminalState)); - assertThat(replay.outcomeCode()).isEqualTo(retained.get().outcome()); - assertThat( - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow())) - .isEqualTo(retained.get()); - assertThat(fixture.countAll("account_audit_outbox")) - .isEqualTo("COMMITTED".equals(terminalState) ? 1L : 0L); - } - - @Test - void browserFacadeReplaysCommittedJoinProofAfterMembershipBecomesInactive() { - Fixture fixture = newFixture(); - BrowserFacade browser = fixture.browserFacade(); - var selected = - browser.service().listBootstrapRealms(browser.bootstrapToken(), "world").getFirst(); - String requestId = UUID.randomUUID().toString(); - var request = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - selected.connectScopeId(), requestId); - - var original = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - fixture.seedControlledInactiveOwnerSnapshot(); - var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); - - assertThat(original.success()).isTrue(); - assertThat(original.outcomeCode()).isEqualTo("JOINED"); - assertThat(original.membershipVersion()).isEqualTo(2L); - assertThat(original.membershipAuthorityGeneration()).isEqualTo(1L); - assertThat(original.gameplayAdmissionAllowed()).isTrue(); - assertThat(replay.success()).isTrue(); - assertThat(replay.outcomeCode()).isEqualTo(original.outcomeCode()); - assertThat(replay.membershipId()).isEqualTo(original.membershipId()); - assertThat(replay.membershipVersion()).isEqualTo(original.membershipVersion()); - assertThat(replay.membershipAuthorityGeneration()) - .isEqualTo(original.membershipAuthorityGeneration()); - assertThat(replay.gameplayAdmissionAllowed()).isFalse(); - assertThat(replay.replayed()).isTrue(); - - var currentMembership = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); - assertThat(currentMembership.getLifecycleState()).isEqualTo("INACTIVE"); - assertThat(currentMembership.getMembershipVersion()).isEqualTo(3L); - assertThat(currentMembership.getMembershipAuthorityGeneration()).isEqualTo(2L); - assertThat(currentMembership.isGameplayAdmissionAllowed()).isFalse(); - } - - @Test - void directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwners() { - Fixture fixture = newFixture(); - BrowserFacade composed = fixture.browserFacade(); - var target = composed.target(); - String requestId = UUID.randomUUID().toString(); - var caller = - new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( - fixture.account.getAccountUuid(), - fixture.tenantUuid, - target.realmId(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - "2001", - requestId); - var selected = - new net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget( - fixture.tenantUuid, - target.realmId(), - target.worldSlug(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion()); - var peer = - new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( - "spiffe://firemud/ns/" + TEST_NAMESPACE + "/sa/game-session-service", - TEST_NAMESPACE, - "game-session-service"); - var context = - io.grpc.Context.ROOT.withValue( - net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer); - context.run( - () -> { - var scope = composed.service().issueDirectTextConnectScope(caller, selected); - var request = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - scope.connectScopeId(), requestId); - var first = composed.service().joinPublicProductionFromGameSession(caller, request); - var replay = composed.service().joinPublicProductionFromGameSession(caller, request); - assertThat(first.success()).isTrue(); - assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); - assertThat(first.membershipVersion()).isEqualTo(2L); - assertThat(first.gameplayAdmissionAllowed()).isTrue(); - assertThat(replay.success()).isTrue(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.membershipId()).isEqualTo(first.membershipId()); - }); - org.mockito.Mockito.verifyNoInteractions(composed.sessions()); - assertThat( - fixture.count( - "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) - .isEqualTo(1L); - assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - } - private Fixture newFixture() { return new Fixture(newTestContext()); } @@ -999,7 +408,7 @@ private Account createAccount() { input.setUsername("canonical-join-" + suffix); input.setEmail("canonical-join-" + suffix + "@example.test"); input.setPasswordHash("integration-fixture-hash"); - // Player role belongs to the canonical tenant membership, not global Account authority. + input.setRole("player"); return inTransaction(() -> accounts.save(input)); } @@ -1044,11 +453,6 @@ private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { private DemoTenantEntitlementRequest entitlementRequest( UUID requestId, DemoTenantEntitlementSnapshot current) { - return entitlementRequest(requestId, current, true); - } - - private DemoTenantEntitlementRequest entitlementRequest( - UUID requestId, DemoTenantEntitlementSnapshot current, boolean allowPublicJoin) { return new DemoTenantEntitlementRequest( requestId, tenantUuid, @@ -1058,7 +462,7 @@ private DemoTenantEntitlementRequest entitlementRequest( current == null ? null : current.tenantAuthorityGeneration(), current == null ? null : current.tenantAuthoritySourceVersion(), true, - allowPublicJoin, + true, true, true, new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); @@ -1087,565 +491,6 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoi () -> terminalCoordinator.commitCanonicalFirstJoin(scope, requestId, callerBinding)); } - private String prepareAnotherJoin() { - String nextRequest = UUID.randomUUID().toString(); - inTransaction( - () -> { - operations.lockAccount(account.getId()); - operations.insertCanonicalIntent(nextRequest, scope, callerBinding); - var policy = demoEntitlements.readCurrent(tenantUuid); - operations.bindCanonicalPolicyEvidence( - nextRequest, - scope, - callerBinding, - policy.allowPublicJoin(), - policy.entitlementVersion()); - return null; - }); - return nextRequest; - } - - private AccountJoinOperationRepository.CanonicalJoinOperationEvidence commitExistingJoin( - String nextRequest) { - return inTransaction( - () -> - terminalCoordinator.commitCanonicalJoin( - scope, nextRequest, callerBinding, null, null, null)); - } - - private BrowserFacade browserFacade() { - var jwt = - new net.firedevops.firemud.common.security.JwtUtil( - "controlled-browser-facade-integration-signing-key-0123456789", 300000L); - var sessions = - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.service.session.SessionService.class); - String bootstrap = - jwt.generateToken( - account.getAccountUuid().toString(), - 300000L, - Map.of( - "aud", - "player-bootstrap", - "accountId", - account.getAccountUuid().toString(), - "jti", - UUID.randomUUID().toString())); - org.mockito.Mockito.when(sessions.isAccountSessionActive(account.getId(), bootstrap)) - .thenReturn(true); - var targets = - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.client - .CanonicalGameplayAdmissionDecisionReadClient.class); - var target = controlledPublishedTarget(); - org.mockito.Mockito.when( - targets.listVisiblePublicProductionAdmissionTargets( - org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var request = - new net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( - invocation.getArgument(0, UUID.class), TEST_NAMESPACE); - return net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, java.util.List.of(target))); - }); - org.mockito.Mockito.when( - targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var selector = - invocation.getArgument( - 0, - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector - .class); - return net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - selector, - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( - selector, target)); - }); - // The protected client is the controlled upstream boundary in this Account SQL composition; - // this fixture does not claim physical GS publication or World lifecycle validation. - org.mockito.Mockito.when( - targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var selector = - invocation.getArgument( - 0, - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .Request.class); - var published = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - org.mockito.Mockito.when(published.selector()).thenReturn(selector); - org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); - return published; - }); - var hosting = - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository - .AccountHostingSubscriptionLifecycleRepository.class); - var observer = - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.class); - var manager = Objects.requireNonNull(transaction.getTransactionManager()); - var clock = java.time.Clock.systemUTC(); - var properties = new net.firedevops.firemud.accountservice.config.AccountTokenProperties(); - properties.setConnectScopeExpirationMs(120000L); - var entitlementOwner = - new net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner( - tenantAuthorityEvents, - new net.firedevops.firemud.accountservice.service - .AccountHostingSubscriptionLifecycleService(hosting, observer, manager), - demoEntitlements, - manager, - clock); - var producerOwner = - new net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner( - new net.firedevops.firemud.accountservice.service.session - .AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions), - targets, - entitlementOwner, - accounts, - memberships, - freshTenants, - tenantAuthorityEvents, - connectScopes, - jwt, - properties, - clock, - manager, - TEST_NAMESPACE); - var service = - new net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl( - accounts, - generations, - sourceEvidence, - outbox, - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository - .AccountPasswordResetOperationRepository.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository - .AccountLogoutAllOperationRepository.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository - .AccountSecurityStateOperationRepository.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.service - .AccountPasswordResetDraftSourceChangeRepository.class), - auditOutbox, - operations, - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository - .AccountEmailLoginChallengeRepository.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository - .class), - memberships, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - new net.firedevops.firemud.accountservice.config.MailProperties(), - properties, - new net.firedevops.firemud.common.security.JwtAuthProperties(), - jwt, - sessions, - manager); - service.setCanonicalPublicRealmScopeOwner(producerOwner); - service.setCanonicalScopeConsumers( - new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( - jwt, connectScopes, manager, clock), - targets, - tenantAuthorityEvents, - demoEntitlements, - hosting, - observer, - terminalCoordinator, - TEST_NAMESPACE, - clock); - return new BrowserFacade(service, bootstrap, target, sessions); - } - - /** - * Protected GS transport remains a controlled owner response; Account SQL/JWT owners are real. - */ - private net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target - controlledPublishedTarget() { - UUID version = UUID.randomUUID(); - String digest = "a".repeat(64); - String initial = UUID.randomUUID().toString(); - var holdRequest = - new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request( - TEST_NAMESPACE, - tenantUuid, - scope.worldSlug(), - scope.realmId(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - version, - 1L, - initial, - digest, - net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold - .InitialAdmissionOrigin.NO_PRIOR_POINTER, - scope.catalogRevision(), - null); - var hold = - new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( - holdRequest, UUID.randomUUID(), UUID.randomUUID()); - return new net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target( - TEST_NAMESPACE, - "tenant", - tenantUuid, - scope.worldSlug(), - "World", - scope.realmId(), - scope.realmSlug(), - "Production", - 11L, - 44L, - scope.playableStateNamespaceId(), - "SHARED", - scope.gameInstanceId(), - version, - 1L, - scope.catalogRevision(), - scope.pointerVersion(), - digest, - 1L, - initial, - digest, - net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec - .OriginKind.NO_PRIOR_POINTER, - null, - hold.holdId(), - hold.holdFence(), - hold.holdBindingDigest(), - 1L, - "sha256:" + digest, - net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec - .OwnerProofOutcome.COMMITTED, - false, - java.time.Instant.now(), - "PRESEEDED_ONLY"); - } - - /** Controlled retained INACTIVE input; this fixture does not claim a production leave owner. */ - private void seedControlledInactiveOwnerSnapshot() { - seedControlledMembershipSnapshot("INACTIVE", java.util.List.of("player")); - } - - /** Controlled owner snapshot; no leave, creator grant or lifecycle mutation API is claimed. */ - @SuppressWarnings("unchecked") - private void seedControlledMembershipSnapshot( - String lifecycle, java.util.List currentRoles) { - // The existing draft source-change owner requires a physical READ_COMMITTED connection. - var historicalTransaction = new TransactionTemplate(transaction.getTransactionManager()); - historicalTransaction.setPropagationBehavior( - org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); - historicalTransaction.setIsolationLevel( - org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); - historicalTransaction.execute( - status -> { - operations.lockAccount(account.getId()); - var member = - memberships - .findFreshMembershipForUpdate(account.getAccountUuid(), tenantUuid) - .orElseThrow(); - var generation = - generations.read( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantUuid)); - // This is controlled historical input, not an implemented leave/role-removal owner. - // One atomic invalidating transaction advances the closed Account source and fence; - // the member generation then advances under that same fence without inventing an - // Account event or weakening the V40 deferred source/fence checks. - var accountBefore = - sourceEvidence.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, account.getAccountUuid()); - commitControlledClosedAccountSecurityChange(accountBefore.account()); - assertThat( - dsl.execute( - "UPDATE account_authority_generations SET generation = generation + 1, " - + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " - + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ? " - + "AND generation = ? AND source_version = ?", - account.getAccountUuid(), - tenantUuid, - generation.generation(), - generation.sourceVersion())) - .isEqualTo(1); - var next = generations.read(generation.scope()); - var authority = - generations.readCompositeSnapshot( - ACCOUNT_ISSUER, - account.getAccountUuid(), - java.util.List.of(tenantUuid), - java.util.List.of(tenantUuid)); - var accountSource = - sourceEvidence.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, account.getAccountUuid()); - assertThat(next.generation()).isEqualTo(generation.generation() + 1L); - assertThat(next.sourceVersion()).isEqualTo(generation.sourceVersion() + 1L); - assertThat(next.issuanceFence().value()) - .isEqualTo(generation.issuanceFence().value() + 1L); - assertThat(next.issuanceFence().sourceVersion()) - .isEqualTo(generation.issuanceFence().sourceVersion() + 1L); - assertThat(accountSource.issuanceFence()).isEqualTo(next.issuanceFence()); - assertThat(accountSource.account().generation()) - .isEqualTo(accountBefore.account().generation() + 1L); - assertThat(accountSource.account().sourceVersion()) - .isEqualTo(accountBefore.account().sourceVersion() + 1L); - assertThat(accountSource.account().checkpoint().sequence()) - .isEqualTo(accountBefore.account().checkpoint().sequence() + 1L); - var tenantSource = tenantAuthorityEvents.readCurrentByTenant(tenantUuid); - var prior = pairs.readForUpdate(account.getAccountUuid(), tenantUuid).orElseThrow(); - var previousEvent = - outbox.findEvent(membershipStream(), prior.eventSequence()).orElseThrow(); - var json = tools.jackson.databind.json.JsonMapper.builder().build(); - Map event = - json.readValue( - new String(previousEvent.payload(), StandardCharsets.UTF_8), Map.class); - String inactiveRequest = "controlled-inactive-" + UUID.randomUUID(); - event.remove("eventDigest"); - event.put("eventId", UUID.randomUUID().toString()); - event.put("requestId", inactiveRequest); - event.put("outboxSequence", "2"); - event.put("membershipLifecycleState", lifecycle); - event.put("roles", currentRoles); - event.put("membershipVersion", Map.of(tenantUuid.toString(), "3")); - event.put("membershipAuthorityGeneration", Long.toString(next.generation())); - Map tuple = new java.util.LinkedHashMap<>(); - tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); - tuple.put( - "accountAuthorityGeneration", Long.toString(authority.account().generation())); - tuple.put( - "tenantAuthorityGeneration", - Map.of( - tenantUuid.toString(), - Long.toString(authority.tenants().getFirst().generation()))); - tuple.put( - "membershipAuthorityGeneration", - Map.of(tenantUuid.toString(), Long.toString(next.generation()))); - tuple.put("privateRealmGrantVersions", java.util.List.of()); - var cutoff = accountSource.account().accountSecurityCutoff().orElseThrow(); - tuple.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence())); - tuple.put( - "tenantBillingCutoff", - Map.of( - tenantUuid.toString(), - Map.of( - "tenantAuthorityGeneration", - Long.toString(tenantSource.tenantAuthorityGeneration()), - "tenantBillingSequence", - Long.toString(tenantSource.tenantBillingSequence()), - "outboxStreamKey", tenantSource.outboxStreamKey(), - "outboxSequence", Long.toString(tenantSource.outboxSequence())))); - event.put("authorityTuple", tuple); - event.put("issuanceFence", Long.toString(next.issuanceFence().value())); - event.put("gameplayAdmissionAllowed", false); - event.put("callerBoundAuthorityInvalidated", true); - var sealed = MembershipAuthorityEventV1Codec.seal(event); - var appended = - outbox.append( - membershipStream(), - inactiveRequest, - sequence -> { - if (sequence != 2L) - throw new IllegalStateException("Controlled inactive sequence changed"); - return new AccountAuthorityOutboxRepository.EventEvidence( - sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); - }); - dsl.execute( - "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = FALSE, " - + "membership_version = 3, membership_authority_generation = 2 WHERE id = ?", - lifecycle, - member.getId()); - var inactive = - memberships - .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantUuid) - .orElseThrow(); - roles.replaceCanonical( - inactive, account.getAccountUuid(), tenantUuid, provenance, 3L, currentRoles); - dsl.execute( - "UPDATE account_membership_pair_authority SET membership_version = 3, membership_authority_generation = 2, " - + "last_event_sequence = 2, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE " - + "WHERE account_uuid = ? AND tenant_uuid = ?", - appended.eventId(), - appended.eventDigest(), - account.getAccountUuid(), - tenantUuid); - return null; - }); - } - - /** - * Controlled sole-writer composition of the existing closed security-state operation. The - * correlation bytes are fixture input, not authenticated permission or a runtime producer. Keep - * the source change, exact receipt, event and head in the enclosing historical transaction. - */ - private void commitControlledClosedAccountSecurityChange( - AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence currentSource) { - var current = accounts.findByIdForUpdate(account.getId()).orElseThrow(); - var roleSource = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT global_roles, global_role_source_version FROM account_global_role_sources " - + "WHERE account_uuid = ? FOR SHARE", - account.getAccountUuid())); - long roleVersion = - Objects.requireNonNull(roleSource.get("global_role_source_version", Long.class)); - var before = - new AccountState( - current.isEmailVerified(), - AccountLoginAuthModes.read(current.getLoginAuthModes()).stream() - .map(Enum::name) - .sorted() - .toList(), - java.util.Arrays.stream(roleSource.get("global_roles", String[].class)) - .sorted() - .toList(), - current.getLifecycleState().name()); - var after = - new AccountState( - !before.emailVerified(), - before.loginAuthModes(), - before.globalRoles(), - before.lifecycleState()); - var sourceState = generations.read(currentSource.scope()); - String stream = currentSource.checkpoint().outboxStreamKey(); - long checkpointSequence = currentSource.checkpoint().sequence(); - byte[] checkpointPayload = - checkpointSequence == 0L - ? new byte[0] - : outbox.findEvent(stream, checkpointSequence).orElseThrow().payload(); - UUID securityRequest = UUID.randomUUID(); - byte[] correlation = - ("{\"actorAccountUuid\":\"" - + account.getAccountUuid() - + "\",\"ownerEvidenceDigest\":\"sha256:" - + "a".repeat(64) - + "\",\"ownerOperationId\":\"" - + securityRequest - + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") - .getBytes(StandardCharsets.UTF_8); - var request = - new AccountSecurityStateMutationRequest( - securityRequest, - account.getAccountUuid(), - correlation, - sourceState.generation(), - sourceState.sourceVersion(), - AccountSecurityStateOperationRepository.detectedKinds(before, after), - after); - var draft = - new Capture( - current.getId(), - current.getAccountUuidProvenance(), - before, - sourceState, - checkpointSequence, - checkpointPayload, - roleVersion, - null); - byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); - var source = - new SourceEvidence( - SourceKind.ACCOUNT, - account.getAccountUuid().toString(), - Long.toString(sourceState.generation()), - Long.toString(sourceState.sourceVersion()), - stream, - Long.toString(checkpointSequence), - captureBytes); - var change = new SourceChange(UUID.randomUUID(), java.util.List.of(source), captureBytes); - var capture = - new Capture( - draft.accountId(), - draft.provenance(), - before, - sourceState, - checkpointSequence, - checkpointPayload, - roleVersion, - change); - var fences = new DraftAuthorizationFenceRepository(dsl); - var securityOperations = new AccountSecurityStateOperationRepository(dsl); - assertThat(fences.requestSourceChange(change)).isTrue(); - assertThat(securityOperations.claim(request, capture).claimed()).isTrue(); - assertThat(fences.sourceMutationPermitted(change)).isTrue(); - var advanced = - sourceEvidence.prepareClosedAccountAdvance(account.getAccountUuid(), currentSource); - assertThat( - dsl.execute( - "UPDATE accounts SET email_verified = ? WHERE account_uuid = ?", - after.emailVerified(), - account.getAccountUuid())) - .isEqualTo(1); - var event = - outbox.append( - stream, - securityRequest.toString(), - sequence -> { - var sealed = - AccountSecurityStateAuthorityEventV1Codec.seal( - AccountSecurityStateMutationRequest.eventPreimage( - securityRequest, - account.getAccountUuid(), - Long.toString(advanced.generation()), - Long.toString(advanced.sourceVersion()), - Long.toString(sequence), - request.mutationKinds(), - after)); - return new AccountAuthorityOutboxRepository.EventEvidence( - sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); - }); - fences.markSourceCommitted(change); - var committed = securityOperations.complete(request, event, advanced, roleVersion); - assertThat(committed.receipt().orElseThrow().event()).isEqualTo(event); - assertThat(committed.capture().sourceChange().canonicalBytes()) - .isEqualTo(change.canonicalBytes()); - assertThat(fences.readSourceChange(change).status()).isEqualTo("SOURCE_COMMITTED"); - } - private long membershipId() { return membershipId == null ? -1L : membershipId; } @@ -1729,12 +574,4 @@ private static long positiveRandomLong() { } private record TestContext(DSLContext dsl, TransactionTemplate transaction) {} - - private record BrowserFacade( - net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl service, - String bootstrapToken, - net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec - .Target - target, - net.firedevops.firemud.accountservice.service.session.SessionService sessions) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java deleted file mode 100644 index aedb15b4be..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java +++ /dev/null @@ -1,399 +0,0 @@ -package integration.net.firedevops.firemud.accountservice.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verifyNoInteractions; - -import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; -import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; -import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; -import org.flywaydb.core.Flyway; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Physical Account transaction and real SDK decoding against a controlled local Stripe transport. - * Tenant/creator/billing setup and the caller/scope are controlled; no authenticated public caller, - * real Stripe, World hold, protected admission transport, custody or runtime activation is proved. - */ -class AccountPaidCanonicalFirstJoinPostgresIntegrationTest { - private static final String PREFIX = "paid_first_join_"; - private static final String CALLER = "controlled-paid-join-caller"; - private static final AccountPostgresIntegrationFixture POSTGRES = - new AccountPostgresIntegrationFixture(); - private final Set schemas = ConcurrentHashMap.newKeySet(); - - @BeforeAll - static void start() { - POSTGRES.start(); - } - - @AfterAll - static void stop() { - POSTGRES.stop(); - } - - @AfterEach - void dropOwnedSchemas() { - var jdbc = new JdbcTemplate(POSTGRES.dataSource()); - for (String schema : schemas) { - if (!schema.startsWith(PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) - throw new IllegalStateException("Refusing unowned schema cleanup"); - jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } - schemas.clear(); - } - - @Test - void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo() { - Context c = context(false); - int reads = c.hosting.transport().reads(); - var first = c.commit(c.observed); - var replay = c.commit(c.observed); - assertThat(replay).isEqualTo(first); - assertThat(c.hosting.transport().reads()).isEqualTo(reads); - assertThat(c.scope.accountId()).isNotEqualTo(c.hosting.accountUuid()); - var retained = - c.hosting.transaction().execute(status -> c.outbox.findEvent(c.stream(), 1L).orElseThrow()); - var event = - MembershipAuthorityEventV1Codec.verify( - new String(Objects.requireNonNull(retained).payload(), StandardCharsets.UTF_8)); - assertThat(event.accountId()).isEqualTo(c.scope.accountId().toString()); - assertThat(event.authorityTuple().tenantBillingCutoff()).isPresent(); - assertThat(event.authorityTuple().tenantAuthorityGeneration()) - .containsKey(c.hosting.tenantId().toString()); - assertThat(c.count("account_tenant_membership")).isEqualTo(1); - assertThat(c.count("account_tenant_membership_role_snapshots")).isEqualTo(1); - assertThat(c.count("account_audit_outbox")).isEqualTo(1); - assertThat(c.operation().status()).isEqualTo("COMMITTED"); - assertThat(c.operation().terminalProof()).isEqualTo(first); - } - - @Test - void providerFactsChangedBeforeCommitRollbackAllStagedWritesThenSameOriginalCanRecover() { - Context c = context(false); - var original = c.operation(); - c.hosting.providerStatus("canceled"); - var contradictory = c.hosting.observer().observe(c.fence.binding()); - assertThatThrownBy(() -> c.commit(contradictory)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("ENTITLEMENT_UNAVAILABLE: provider facts differ from the committed receipt"); - verifyNoInteractions(c.demos); - c.assertRolledBack(original); - c.hosting.providerStatus("active"); - var recovered = c.hosting.observer().observe(c.fence.binding()); - var committed = c.commit(recovered); - assertThat(committed.entitlementVersion()).isEqualTo(original.entitlementVersion()); - assertThat(c.count("account_tenant_membership")).isEqualTo(1); - assertThat(c.count("account_audit_outbox")).isEqualTo(1); - } - - @Test - void changedOperationPolicyCannotCommitAgainstAnOlderPaidReceipt() { - Context c = context(true); - var original = c.operation(); - assertThatThrownBy(() -> c.commit(c.observed)) - .hasMessageContaining("exact current public-join entitlement"); - c.assertRolledBack(original); - } - - @Test - void expiredPaidReceiptIsUnavailableAndNeverSelectsDemo() { - Context c = context(false); - var original = c.operation(); - c.hosting.clock().advance(Duration.ofHours(2)); - var freshSdkResult = c.hosting.observer().observe(c.fence.binding()); - assertThatThrownBy(() -> c.commit(freshSdkResult)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("ENTITLEMENT_UNAVAILABLE: current receipt is expired or inconsistent"); - verifyNoInteractions(c.demos); - c.assertRolledBack(original); - } - - @Test - void finalCommitFailureRollsBackMembershipRolesPairEventAuditAndTerminalReceipt() { - Context c = context(false); - var original = c.operation(); - assertThatThrownBy( - () -> - c.hosting - .transaction() - .execute( - status -> { - TransactionSynchronizationManager.registerSynchronization( - new TransactionSynchronization() { - @Override - public void beforeCommit(boolean readOnly) { - throw new IllegalStateException( - "controlled final paid JOIN commit refusal"); - } - }); - return c.coordinator.commitPaidCanonicalFirstJoin( - c.scope, - c.requestId, - CALLER, - c.hosting.lifecycleRepository(), - c.fence, - c.observed); - })) - .hasMessageContaining("controlled final paid JOIN commit refusal"); - c.assertRolledBack(original); - } - - private Context context(boolean wrongPolicy) { - String schema = PREFIX + UUID.randomUUID().toString().replace("-", ""); - schemas.add(schema); - var source = POSTGRES.dataSource(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); - return new Context(CanonicalHostingSubscriptionTestFixture.create(source), wrongPolicy); - } - - private static final class Context { - private final CanonicalHostingSubscriptionTestFixture.Fixture hosting; - private final AccountJoinOperationRepository operations; - private final AccountAuthorityOutboxRepository outbox; - private final AccountDemoTenantEntitlementRepository demos; - private final AccountMembershipPairAuthorityRepository pairs; - private final AccountCanonicalFirstJoinTerminalCoordinator coordinator; - private final CanonicalJoinScopeV2 scope; - private final String requestId = UUID.randomUUID().toString(); - private final ReadFence fence; - private final StripeHostingSubscriptionObserver.Result observed; - - private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean wrongPolicy) { - this.hosting = hosting; - var claim = - hosting - .service() - .claimProvisioning(hosting.creation().requestId(), 1, UUID.randomUUID()) - .claim(); - var committed = - hosting - .service() - .reconcile( - UUID.randomUUID(), - hosting.creation().requestId(), - claim.subscriptionRowVersion(), - hosting.providerId(), - claim.attemptId()); - assertThat(committed.outcome()) - .isEqualTo( - net.firedevops.firemud.accountservice.repository - .AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); - hosting.transaction().setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - var dsl = hosting.dsl(); - var accounts = new AccountRepository(dsl); - var fresh = new FreshTenantIdentityAssociationRepository(dsl, "prod"); - pairs = new AccountMembershipPairAuthorityRepository(dsl); - var members = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); - var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); - var generations = new AccountAuthorityGenerationRepository(dsl); - outbox = new AccountAuthorityOutboxRepository(dsl); - var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - var billing = new AccountTenantEntitlementOutboxRepository(dsl); - var tenantEvents = - new AccountTenantAuthorityEventRepository(dsl, outbox, billing, fresh, generations); - demos = - spy( - new AccountDemoTenantEntitlementRepository( - dsl, fresh, generations, billing, tenantEvents)); - var scopes = - new AccountConnectScopeRepository( - dsl, - new AccountTenantIdentityResolver( - mock(ApprovedLegacyTenantAssociationRepository.class), "prod"), - fresh); - operations = new AccountJoinOperationRepository(dsl, scopes); - var producer = - new AccountMembershipAuthorityEventProducer( - operations, - accounts, - pairs, - members, - roles, - generations, - outbox, - sources, - tenantEvents, - demos); - coordinator = - new AccountCanonicalFirstJoinTerminalCoordinator( - accounts, - operations, - members, - roles, - outbox, - pairs, - new AccountAuditOutboxRepository(dsl), - producer); - Account input = new Account(); - input.setUsername("paid-player-" + UUID.randomUUID()); - input.setEmail("paid-player-" + UUID.randomUUID() + "@example.test"); - input.setPasswordHash("controlled-hash"); - // Player role belongs to the canonical tenant membership, not global Account authority. - Account player = - Objects.requireNonNull(hosting.transaction().execute(status -> accounts.save(input))); - var now = hosting.clock().instant(); - scope = - new CanonicalJoinScopeV2( - "controlled-paid-scope-" + UUID.randomUUID(), - player.getAccountUuid(), - hosting.tenantId(), - UUID.randomUUID(), - "tenant", - "world", - "production", - UUID.randomUUID(), - "SHARED", - UUID.randomUUID(), - 7, - 3, - now.toString(), - now.plusSeconds(120).toString()); - hosting - .transaction() - .executeWithoutResult( - status -> { - var source = fresh.read(hosting.tenantId()).orElseThrow(); - sources.initializeIssuerIfAbsent("firemud-account-service"); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - player.getAccountUuid(), hosting.tenantId())); - scopes.insertCanonical( - player.getId(), - scope, - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - source.operationId(), - source.evidenceDigest())); - operations.insertCanonicalIntent(requestId, scope, CALLER); - }); - fence = - Objects.requireNonNull( - hosting - .transaction() - .execute( - status -> - hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); - observed = hosting.observer().observe(fence.binding()); - hosting - .transaction() - .executeWithoutResult( - status -> { - var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - CALLER, - receipt.allowPublicJoin(), - receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); - }); - } - - private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( - StripeHostingSubscriptionObserver.Result result) { - return Objects.requireNonNull( - hosting - .transaction() - .execute( - status -> - coordinator.commitPaidCanonicalFirstJoin( - scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); - } - - private AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation() { - return Objects.requireNonNull( - hosting - .transaction() - .execute( - status -> { - operations.lockAccount( - Objects.requireNonNull( - hosting - .dsl() - .fetchOne( - "SELECT id FROM accounts WHERE account_uuid = ?", - scope.accountId())) - .get(0, Long.class)); - return operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - })); - } - - private String stream() { - return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX - + "membership/" - + scope.accountId() - + "/" - + scope.tenantId(); - } - - private int count(String table) { - return hosting.dsl().fetchCount(DSL.table(table)); - } - - private void assertRolledBack( - AccountJoinOperationRepository.CanonicalJoinOperationEvidence original) { - assertThat(operation()).isEqualTo(original); - assertThat(count("account_tenant_membership")).isZero(); - assertThat(count("account_tenant_membership_role_snapshots")).isZero(); - assertThat(count("account_audit_outbox")).isZero(); - var checkpoint = hosting.transaction().execute(status -> outbox.readCheckpoint(stream())); - assertThat(checkpoint).isEmpty(); - var pair = - hosting - .transaction() - .execute(status -> pairs.readForUpdate(scope.accountId(), scope.tenantId())); - assertThat(pair).isEmpty(); - } - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java deleted file mode 100644 index 9c5f6a9b38..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ /dev/null @@ -1,329 +0,0 @@ -package net.firedevops.firemud.accountservice.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; -import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner.Request; -import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; -import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Real Account SQL/current-source readers and real Stripe SDK over controlled read-only transport. - * Enrollment inputs and provider transport are controlled; no mTLS, registration, live Stripe, - * player producer/consumer, durable evaluation replay, or capacity-commit proof is claimed. - */ -@Testcontainers(disabledWithoutDocker = true) -class AccountTenantOperationEntitlementOwnerPostgresIntegrationTest { - private static final String WORLD = "spiffe://firemud/ns/prod/sa/world-management-service"; - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void reusedAccountFixtureKeepsConfirmedCustomerAndObservationHistoryUnchanged() { - var first = context().fixture(); - Account existing = new Account(); - existing.setId(first.accountId()); - existing.setAccountUuid(first.accountUuid()); - var customerBefore = - first - .dsl() - .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM billing_customer t") - .intoMaps(); - var observationsBefore = - first - .dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM account_billing_customer_observations t") - .intoMaps(); - assertThat( - java.util.Objects.requireNonNull( - first.dsl().fetchOne("SELECT row_version FROM billing_customer")) - .get(0, Long.class)) - .isGreaterThan(1L); - - var second = - CanonicalHostingSubscriptionTestFixture.create( - java.util.Objects.requireNonNull(first.jdbc().getDataSource()), existing); - - assertThat(second.accountUuid()).isEqualTo(first.accountUuid()); - assertThat(second.tenantId()).isNotEqualTo(first.tenantId()); - assertThat(second.creation().providerCustomerId()) - .isEqualTo(first.creation().providerCustomerId()); - assertThat( - first - .dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM billing_customer t") - .intoMaps()) - .isEqualTo(customerBefore); - assertThat( - first - .dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM account_billing_customer_observations t") - .intoMaps()) - .isEqualTo(observationsBefore); - } - - @Test - void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnapshot() { - Context c = context(); - var f = c.fixture(); - var claim = - f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); - var committed = - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()); - assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); - int beforeReads = f.transport().reads(); - UUID requestId = UUID.randomUUID(); - var first = c.owner().evaluatePaid(new Request(f.tenantId(), requestId, WORLD)); - f.clock().advance(java.time.Duration.ofSeconds(30)); - var second = c.owner().evaluatePaid(new Request(f.tenantId(), requestId, WORLD)); - assertThat(f.transport().reads()).isEqualTo(beforeReads + 2); - assertThat(first.fields()) - .containsEntry("sourceKind", "PAID_HOSTING") - .containsEntry("subscriptionStatus", "active") - .containsEntry("provisioningStatus", null) - .containsEntry("allowNewInstanceStarts", true) - .containsEntry("callerWorkload", WORLD) - .containsEntry("requestId", requestId.toString()); - assertThat(first.fields().get("snapshotIdentity")) - .isEqualTo(second.fields().get("snapshotIdentity")); - assertThat(first.fields().get("evaluationIdentity")) - .isNotEqualTo(second.fields().get("evaluationIdentity")); - assertThat(java.time.Instant.parse((String) second.fields().get("evaluatedAt"))) - .isAfter(java.time.Instant.parse((String) first.fields().get("evaluatedAt"))); - assertThat(first.fields()) - .doesNotContainKeys("callerAccountId", "issuer", "accountId", "verifiedConnectScopeId"); - assertThat(first.fields().get("quotas")) - .isEqualTo( - Map.of( - "maxActiveSessions", - "100", - "maxConcurrentGameInstances", - "2", - "maxStorageBytes", - "1048576")); - assertActualTenantCheckpoint(c, first); - assertThat(RuntimeTenantOperationEntitlementEvidence.parseCanonical(first.canonicalBytes())) - .isEqualTo(first); - - f.providerStatus("canceled"); - assertThatThrownBy( - () -> c.owner().evaluatePaid(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - } - - @Test - void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { - Context c = context(); - var f = c.fixture(); - var claim = - f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); - var committed = - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()); - assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); - String marker = "capture_marker_" + UUID.randomUUID().toString().replace("-", ""); - AtomicInteger captures = new AtomicInteger(); - assertThatThrownBy( - () -> - f.service() - .readCurrentAndCapture( - f.tenantId(), - receipt -> { - captures.incrementAndGet(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat( - TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - f.dsl().execute("CREATE TABLE " + marker + " (id bigint)"); - throw new IllegalStateException("controlled capture rollback"); - })) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE") - .hasCauseInstanceOf(IllegalStateException.class) - .hasRootCauseMessage("controlled capture rollback"); - assertThat(captures).hasValue(1); - assertThat(f.dsl().fetchSingle("SELECT to_regclass(?)::text", marker).get(0, String.class)) - .isNull(); - } - - @Test - void pendingDoesNotBecomePositiveAndExplicitDemoUsesOnlyItsActualCurrentOwner() { - Context c = context(); - var f = c.fixture(); - assertThatThrownBy( - () -> c.owner().evaluatePaid(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThatThrownBy( - () -> c.owner().evaluateDemo(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) - .isInstanceOf(RuntimeException.class); - var tenantSources = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); - var committed = - f.transaction() - .execute( - status -> { - var source = tenantSources.read(f.tenantId()).orElseThrow(); - return c.demos() - .provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - f.tenantId(), - source.creationRequestId(), - source.requestDigest(), - null, - null, - null, - true, - false, - true, - false, - new DemoTenantEntitlementRequest.Quotas(3, 1, 500)), - source); - }); - assertThat(committed).isNotNull(); - int beforeReads = f.transport().reads(); - var evaluated = c.owner().evaluateDemo(new Request(f.tenantId(), UUID.randomUUID(), WORLD)); - assertThat(evaluated.fields()) - .containsEntry("sourceKind", "NON_PAID_DEMO") - .containsEntry("subscriptionStatus", null) - .containsEntry("provisioningStatus", null) - .containsEntry("gameplayAvailable", true) - .containsEntry("allowPublicJoin", false) - .containsEntry("allowNewGameplayBindings", true) - .containsEntry("allowNewInstanceStarts", false); - assertActualTenantCheckpoint(c, evaluated); - assertThat(f.transport().reads()).isEqualTo(beforeReads); - assertThatThrownBy( - () -> c.owner().evaluatePaid(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - } - - @Test - void wrongWorkloadNamespaceAndPlayerRequestsFailBeforeSourceReads() { - Context c = context(); - var f = c.fixture(); - assertThatThrownBy( - () -> - c.owner() - .evaluatePaid( - new Request( - f.tenantId(), - UUID.randomUUID(), - "spiffe://firemud/ns/another/sa/world-management-service"))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Request( - f.tenantId(), - UUID.randomUUID(), - "spiffe://firemud/ns/prod/sa/game-session-service")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new Request(new UUID(0L, 0L), UUID.randomUUID(), WORLD)) - .isInstanceOf(IllegalArgumentException.class); - assertThat(f.transport().reads()).isZero(); - } - - @SuppressWarnings("unchecked") - private static void assertActualTenantCheckpoint( - Context c, RuntimeTenantOperationEntitlementEvidence value) { - var expected = - c.fixture() - .transaction() - .execute( - status -> - new AccountAuthorityOutboxRepository(c.fixture().dsl()) - .readCheckpoint( - TenantAuthorityEventV1Codec.streamKey(c.fixture().tenantId())) - .orElseThrow()); - assertThat(expected).isNotNull(); - var actual = (List>) value.fields().get("outboxCheckpoints"); - assertThat(actual) - .containsExactly( - Map.of( - "outboxStreamKey", - expected.outboxStreamKey(), - "outboxSequence", - Long.toString(expected.outboxSequence()), - "sourceEventId", - expected.sourceEventId(), - "sourceEventDigest", - expected.sourceEventDigest())); - } - - private static Context context() { - String schema = "tenant_operation_" + UUID.randomUUID().toString().replace("-", ""); - var source = - new DriverManagerDataSource( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - source.setSchema(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration", "classpath:db/migration/saga") - .load() - .migrate(); - var f = CanonicalHostingSubscriptionTestFixture.create(source); - var identities = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); - var generations = new AccountAuthorityGenerationRepository(f.dsl()); - var billing = new AccountTenantEntitlementOutboxRepository(f.dsl()); - var tenantEvents = - new AccountTenantAuthorityEventRepository( - f.dsl(), - new AccountAuthorityOutboxRepository(f.dsl()), - billing, - identities, - generations); - var demos = - new AccountDemoTenantEntitlementRepository( - f.dsl(), identities, generations, billing, tenantEvents); - var owner = - new AccountTenantOperationEntitlementOwner( - f.service(), demos, new DataSourceTransactionManager(source), f.clock(), "prod"); - return new Context(f, demos, owner); - } - - private record Context( - CanonicalHostingSubscriptionTestFixture.Fixture fixture, - AccountDemoTenantEntitlementRepository demos, - AccountTenantOperationEntitlementOwner owner) {} -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java deleted file mode 100644 index 5a122c2d0b..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java +++ /dev/null @@ -1,587 +0,0 @@ -package net.firedevops.firemud.accountservice.service.session; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; -import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture.Fixture; -import java.nio.file.Path; -import java.time.Duration; -import java.time.OffsetDateTime; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; -import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; -import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture.IssuedAccount; -import net.firedevops.firemud.accountservice.service.session.AccountHostingSubscriptionTerminalResolutionService.Input; -import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.test.TestContainerImages; -import org.jooq.DSLContext; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.Network; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Coupled genuine Account issuance/current actor, primary authentication and PostgreSQL - * cancellation proof. Policy/signer platform inputs and Stripe transport remain controlled. - * Physical Redis primary/replica AOF acknowledgement executes; no deployed custody, provider - * cancellation, public registration, transfer, provider absence or runtime activation is - * established. - */ -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -class AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest { - private static final String PASSWORD = "test-only-terminal-resolution-password"; - private static final String OTP = "test-only-terminal-resolution-otp"; - private static final Network NETWORK = Network.newNetwork(); - - @Container - static final PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - static final GenericContainer redis = - new GenericContainer<>(TestContainerImages.redis()) - .withNetwork(NETWORK) - .withNetworkAliases("terminal-resolution-primary") - .withExposedPorts(6379) - .withCommand( - "redis-server", - "--bind", - "0.0.0.0", - "--protected-mode", - "no", - "--appendonly", - "yes", - "--appendfsync", - "always"); - - @Container - static final GenericContainer replica = - new GenericContainer<>(TestContainerImages.redis()) - .withNetwork(NETWORK) - .dependsOn(redis) - .withCommand( - "redis-server", - "--bind", - "0.0.0.0", - "--protected-mode", - "no", - "--appendonly", - "yes", - "--appendfsync", - "always", - "--replicaof", - "terminal-resolution-primary", - "6379"); - - @TempDir Path temporary; - - @Test - void actualAccountAndFreshOtpCommitOneAtomicCancellationAndAuthenticatedReplay() - throws Exception { - try (var accountOwners = accountOwners()) { - var failed = failedHosting(accountOwners); - var issued = failed.issued(); - var hosting = failed.hosting(); - var actor = issued.actors().authenticateAccount(issued.compact()); - var issuance = - hosting - .dsl() - .fetchSingle( - "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", - actor.issuanceOperationId()); - assertThat(issuance.get("authorization_scope", String.class)).isEqualTo("ACCOUNT"); - assertThat(issuance.get("tenant_uuid", UUID.class)).isNull(); - assertThat(issuance.get("account_uuid", UUID.class)).isEqualTo(hosting.accountUuid()); - assertThat(issuance.get("status", String.class)).isEqualTo("COMMITTED"); - assertThat(issuance.get("token_hash", String.class)).isEqualTo(actor.tokenHash()); - assertThat(hosting.accountId()).isEqualTo(issued.account().getId()); - assertThat(hosting.accountUuid()).isEqualTo(actor.accountId()); - assertThat( - hosting - .dsl() - .fetchSingle( - "SELECT count(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", - hosting.accountId(), - hosting.tenantId()) - .get(0, Long.class)) - .isZero(); - - issued.sources().installGlobalOtp(issued.account(), OTP); - long auditBefore = count(hosting, "account_audit_outbox"); - int readsBefore = hosting.transport().reads(); - var result = resolve(failed, issued.account().getEmail(), OTP); - assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); - assertThat(hosting.transport().reads()).isEqualTo(readsBefore + 1); - assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())).isEmpty(); - assertCommittedCancellation(failed, result); - assertThat(count(hosting, "account_audit_outbox")).isEqualTo(auditBefore + 1); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - assertThat(hosting.service().readCurrent(hosting.tenantId()).subscriptionStatus()) - .isEqualTo(Status.CANCELED); - - var committed = financialImage(failed); - int readsAfterCommit = hosting.transport().reads(); - // Exact replay authenticates the real current actor but needs neither OTP nor another SDK - // read. - assertThat(service(failed).resolve(issued.compact(), null, null, failed.input())) - .isEqualTo(result); - assertThat(hosting.transport().reads()).isEqualTo(readsAfterCommit); - assertThat(financialImage(failed)).isEqualTo(committed); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - } - } - - @Test - void wrongPrimaryCredentialRetainsFinancialFenceAndUnconsumedOtp() throws Exception { - try (var accountOwners = accountOwners()) { - var failed = failedHosting(accountOwners); - var issued = failed.issued(); - var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); - var before = financialImage(failed); - assertThatThrownBy( - () -> resolve(failed, issued.account().getEmail(), "wrong-test-credential")) - .isInstanceOfSatisfying( - AuthenticationException.class, - failure -> assertThat(failure.getCode()).isEqualTo("AUTH_INVALID_CREDENTIALS")); - assertThat(financialImage(failed)).isEqualTo(before); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - // Real failed-login accounting may advance; it must not consume the challenge. - assertThat(issued.sources().challenges.findByAccountId(failed.hosting().accountId())) - .isPresent() - .get() - .extracting(value -> value.getId()) - .isEqualTo(challenge.getId()); - } - } - - @Test - void lateBillingSqlFailureRollsBackCancellationAndOtpThenSameOtpSucceeds() throws Exception { - try (var accountOwners = accountOwners()) { - var failed = failedHosting(accountOwners); - var issued = failed.issued(); - var hosting = failed.hosting(); - var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); - var before = financialImage(failed); - hosting - .dsl() - .execute( - "CREATE FUNCTION reject_resolution_billing() RETURNS trigger LANGUAGE plpgsql AS $$ " - + "BEGIN RAISE EXCEPTION 'controlled resolution billing failure' USING ERRCODE = '23514'; END; $$"); - hosting - .dsl() - .execute( - "CREATE TRIGGER reject_resolution_billing BEFORE INSERT ON account_tenant_entitlement_outbox_events " - + "FOR EACH ROW EXECUTE FUNCTION reject_resolution_billing()"); - try { - assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) - .hasStackTraceContaining("controlled resolution billing failure"); - assertThat(financialImage(failed)).isEqualTo(before); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())) - .contains(challenge); - } finally { - hosting - .dsl() - .execute( - "DROP TRIGGER reject_resolution_billing ON account_tenant_entitlement_outbox_events"); - hosting.dsl().execute("DROP FUNCTION reject_resolution_billing()"); - } - var result = resolve(failed, issued.account().getEmail(), OTP); - assertCommittedCancellation(failed, result); - assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())).isEmpty(); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - } - } - - @Test - void missingFailedOperationCopyRejectsBeforeCurrentCasAndRollsBackAuditJournalAndOtp() - throws Exception { - try (var accountOwners = accountOwners()) { - var failed = failedHosting(accountOwners); - var issued = failed.issued(); - var hosting = failed.hosting(); - var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); - var before = financialImage(failed); - hosting - .dsl() - .execute( - "CREATE FUNCTION suppress_resolution_operation() RETURNS trigger LANGUAGE plpgsql AS $$ " - + "BEGIN RETURN NULL; END; $$"); - hosting - .dsl() - .execute( - "CREATE TRIGGER suppress_resolution_operation BEFORE INSERT ON subscription_lifecycle_operations " - + "FOR EACH ROW WHEN (NEW.request_id = '" - + failed.input().resolutionRequestId() - + "'::uuid) EXECUTE FUNCTION suppress_resolution_operation()"); - try { - // A controlled row trigger makes INSERT...SELECT affect zero rows despite the locked - // original still existing. The exact copy must fail before the current-row CAS. - assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) - .isExactlyInstanceOf(FenceRejectedException.class) - .hasMessage("Terminal resolution exact failed-operation copy rejected"); - assertThat(financialImage(failed)).isEqualTo(before); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())) - .contains(challenge); - } finally { - hosting - .dsl() - .execute( - "DROP TRIGGER suppress_resolution_operation ON subscription_lifecycle_operations"); - hosting.dsl().execute("DROP FUNCTION suppress_resolution_operation()"); - } - var result = resolve(failed, issued.account().getEmail(), OTP); - assertCommittedCancellation(failed, result); - assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())).isEmpty(); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - } - } - - @Test - void genericAccountAuthorityAdvanceDuringSdkReadMakesSourceUnavailableAndKeepsOtp() - throws Exception { - try (var accountOwners = accountOwners()) { - var failed = failedHosting(accountOwners); - var issued = failed.issued(); - var hosting = failed.hosting(); - var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); - var before = financialImage(failed); - var generations = new AccountAuthorityGenerationRepository(hosting.dsl()); - var authorityBefore = - issued - .sources() - .tx(() -> generations.read(AuthorityScope.account(hosting.accountUuid()))); - hosting - .transport() - .duringRead( - () -> - issued - .sources() - .tx( - () -> { - var account = - issued - .sources() - .accounts - .findById(hosting.accountId()) - .orElseThrow(); - account.setRole("admin"); - // Generic authority events lack the closed operation receipt required - // by current-source readback, so this advance must fail closed there. - return issued.sources().accounts.save(account); - })); - assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) - .isExactlyInstanceOf(SourceEvidenceUnavailableException.class) - .hasMessage("Account authority source evidence is unavailable or inconsistent"); - var authorityAfter = - issued - .sources() - .tx(() -> generations.read(AuthorityScope.account(hosting.accountUuid()))); - assertThat(authorityAfter.generation()).isGreaterThan(authorityBefore.generation()); - assertThat(authorityAfter.issuanceFence().value()) - .isGreaterThan(authorityBefore.issuanceFence().value()); - // The deliberately changed ACCOUNT authority/source rows are outside this financial image. - assertThat(financialImage(failed)).isEqualTo(before); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())) - .contains(challenge); - } - } - - @Test - void otherCertifiedAccountsFreshOtpCannotAuthorizeBillingOwnerAndConsumptionRollsBack() - throws Exception { - try (var accountOwners = accountOwners()) { - var failed = failedHosting(accountOwners); - var other = accountOwners.issueCertifiedAccount("test-only-other-account-password"); - assertThat(other.actors().authenticateAccount(other.compact()).accountId()) - .isNotEqualTo(failed.hosting().accountUuid()); - var challenge = other.sources().installGlobalOtp(other.account(), OTP); - var before = financialImage(failed); - assertThatThrownBy(() -> resolve(failed, other.account().getEmail(), OTP)) - .isInstanceOf(FenceRejectedException.class) - .hasMessageContaining("another Account"); - assertThat(financialImage(failed)).isEqualTo(before); - assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); - assertThat(other.sources().challenges.findByAccountId(other.account().getId())) - .contains(challenge); - } - } - - private AccountControlUiOriginalOrderFixture accountOwners() throws Exception { - return new AccountControlUiOriginalOrderFixture( - postgres.getJdbcUrl(), - postgres.getUsername(), - postgres.getPassword(), - redis.getHost(), - redis.getMappedPort(6379), - temporary); - } - - private static FailedHosting failedHosting(AccountControlUiOriginalOrderFixture accountOwners) { - var issued = accountOwners.issueCertifiedAccount(PASSWORD); - var hosting = - CanonicalHostingSubscriptionTestFixture.create( - Objects.requireNonNull(issued.sources().manager.getDataSource()), issued.account()); - var claim = - Objects.requireNonNull( - hosting - .service() - .claimProvisioning(hosting.creation().requestId(), 1, UUID.randomUUID()) - .claim()); - UUID failedRequest = UUID.randomUUID(); - hosting.providerStatus("incomplete"); - Outcome outcome = null; - // This shared fixture owns a four-attempt/three-stall bound; retain one original operation. - for (int attempt = 0; attempt < 4; attempt++) { - outcome = - hosting - .service() - .reconcile( - failedRequest, - hosting.creation().requestId(), - claim.subscriptionRowVersion(), - hosting.providerId(), - claim.attemptId()) - .outcome(); - if (outcome == Outcome.TERMINAL_FAILURE) break; - assertThat(outcome).isEqualTo(Outcome.RECONCILING); - hosting.clock().advance(Duration.ofSeconds(2)); - } - assertThat(outcome).isEqualTo(Outcome.TERMINAL_FAILURE); - long failedVersion = - hosting - .dsl() - .fetchSingle( - "SELECT row_version FROM subscription_lifecycle_operations WHERE request_id = ?", - failedRequest) - .get(0, Long.class); - long subscriptionVersion = - hosting.intents().findCurrentByTenant(hosting.tenantId()).orElseThrow().rowVersion(); - var input = - new Input( - UUID.randomUUID(), - failedRequest, - hosting.creation().requestId(), - hosting.creation().subscriptionId(), - hosting.tenantId(), - failedVersion, - subscriptionVersion, - UUID.randomUUID(), - "Same-owner recovery from independently observed terminal cancellation"); - hosting.providerStatus("canceled"); - var failed = new FailedHosting(issued, hosting, input, null); - return new FailedHosting(issued, hosting, input, failureImage(failed)); - } - - private static AccountHostingSubscriptionTerminalResolutionService service(FailedHosting failed) { - return new AccountHostingSubscriptionTerminalResolutionService( - failed.issued().actors(), - failed.issued().sources().primary, - failed.hosting().lifecycleRepository(), - failed.hosting().observer(), - failed.hosting().clock()); - } - - private static TransitionResult resolve(FailedHosting failed, String email, String secret) { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return service(failed).resolve(failed.issued().compact(), email, secret, failed.input()); - } - - private static void assertCommittedCancellation(FailedHosting failed, TransitionResult result) { - var hosting = failed.hosting(); - var input = failed.input(); - assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); - assertThat(result.committedRowVersion()).isEqualTo(input.expectedSubscriptionVersion() + 2); - var actor = failed.issued().actors().authenticateAccount(failed.issued().compact()); - var journal = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM subscription_lifecycle_terminal_resolutions " - + "WHERE resolution_request_id = ?", - input.resolutionRequestId()); - assertThat(journal.get("actor_account_id", UUID.class)).isEqualTo(actor.accountId()); - assertThat(journal.get("control_ui_issuance_operation_id", UUID.class)) - .isEqualTo(actor.issuanceOperationId()); - assertThat(journal.get("control_ui_token_hash", String.class)).isEqualTo(actor.tokenHash()); - assertThat(journal.get("authorization_outcome", String.class)) - .isEqualTo("PRIMARY_AUTHENTICATED"); - assertThat(journal.get("state", String.class)).isEqualTo("COMMITTED"); - assertThat(journal.get("authenticated_at", OffsetDateTime.class).toInstant()) - .isEqualTo(hosting.clock().instant()); - var receipt = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM subscription_lifecycle_receipts WHERE request_id = ?", - input.resolutionRequestId()); - assertThat(receipt.get("status", String.class)).isEqualTo("canceled"); - assertThat(receipt.get("receipt_digest", String.class)) - .isEqualTo(journal.get("receipt_digest")); - assertThat(receipt.get("subscription_row_version", Long.class)) - .isEqualTo(result.committedRowVersion()); - assertThat(receipt.get("committed_transaction_id", Long.class)) - .isEqualTo(journal.get("created_transaction_id", Long.class)); - var subscription = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM subscription WHERE subscription_id = ?", - input.subscriptionId()); - assertThat(subscription.get("status", String.class)).isEqualTo("canceled"); - assertThat(subscription.get("lifecycle_inflight_request_id", UUID.class)).isNull(); - assertThat(subscription.get("current_receipt_request_id", UUID.class)) - .isEqualTo(input.resolutionRequestId()); - assertThat(subscription.get("row_version", Long.class)).isEqualTo(result.committedRowVersion()); - var reservation = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM subscription_instrument_reservations WHERE request_id = ?", - input.creationRequestId()); - assertThat(reservation.get("released_at")).isNotNull(); - assertThat(reservation.get("terminal_resolution_id", UUID.class)) - .isEqualTo(subscription.get("terminal_resolution_id", UUID.class)); - var terminal = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM subscription_provider_terminal_resolutions WHERE resolution_id = ?", - subscription.get("terminal_resolution_id", UUID.class)); - assertThat(terminal.get("outcome", String.class)).isEqualTo("CANCELED"); - assertThat(terminal.get("provider_subscription_id", String.class)) - .isEqualTo(hosting.providerId()); - var audit = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM account_audit_outbox WHERE audit_event_id = ?", - input.auditEventId()); - assertThat(audit.get("event_type", String.class)) - .isEqualTo("HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED"); - assertThat(audit.get("payload_digest", String.class)).isEqualTo(journal.get("request_digest")); - var billing = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM account_tenant_entitlement_outbox_events " - + "WHERE tenant_uuid = ? AND request_id = ?", - hosting.tenantId(), - input.resolutionRequestId()); - assertThat(billing.get("event_id", UUID.class)) - .isEqualTo(receipt.get("billing_event_id", UUID.class)); - assertThat(billing.get("event_digest", String.class)) - .isEqualTo(receipt.get("billing_event_digest")); - var authority = - hosting - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS row_xmin FROM account_authority_outbox_events " - + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", - TenantAuthorityEventV1Codec.streamKey(hosting.tenantId()), - receipt.get("authority_sequence", Long.class)); - var event = TenantAuthorityEventV1Codec.verify(authority.get("payload", byte[].class)); - assertThat(event.eventDigest()).isEqualTo(receipt.get("authority_event_digest", String.class)); - assertThat(event.tenantBillingSequence()) - .isEqualTo(receipt.get("billing_sequence", Long.class)); - for (var row : - List.of(receipt, subscription, reservation, terminal, audit, billing, authority)) { - assertThat(row.get("row_xmin", String.class)) - .isEqualTo(journal.get("row_xmin", String.class)); - } - assertThat(count(hosting, "subscription_lifecycle_terminal_resolutions")).isOne(); - assertThat(count(hosting, "subscription_lifecycle_receipts")).isOne(); - assertThat(count(hosting, "subscription_provider_terminal_resolutions")).isOne(); - } - - private static long count(Fixture hosting, String table) { - return hosting.dsl().fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); - } - - private static String failureImage(FailedHosting failed) { - return failed - .hosting() - .dsl() - .fetchSingle( - "SELECT to_jsonb(operation)::text || operation.xmin::text || to_jsonb(notice)::text || notice.xmin::text " - + "FROM subscription_lifecycle_operations operation JOIN subscription_lifecycle_operator_outbox notice " - + "USING (request_id) WHERE request_id = ?", - failed.input().failedRequestId()) - .get(0, String.class); - } - - private static Map financialImage(FailedHosting failed) { - Map image = new LinkedHashMap<>(); - DSLContext dsl = failed.hosting().dsl(); - for (String table : - List.of( - "subscription", - "subscription_current_observations", - "subscription_provisioning_work", - "subscription_lifecycle_operations", - "subscription_lifecycle_attempts", - "subscription_lifecycle_observations", - "subscription_lifecycle_receipts", - "subscription_lifecycle_terminal_resolutions", - "subscription_lifecycle_operator_outbox", - "subscription_provider_history", - "subscription_provider_terminal_resolutions", - "subscription_instrument_reservations", - "account_audit_outbox", - "account_tenant_entitlement_outbox_events", - "account_tenant_entitlement_outbox_streams", - "account_tenant_authority_source_records")) { - image.put(table, rows(dsl, table, "")); - } - image.put( - "tenant_generations", - rows(dsl, "account_authority_generations", " WHERE scope_kind = 'TENANT'")); - String stream = TenantAuthorityEventV1Codec.streamKey(failed.hosting().tenantId()); - for (String table : - List.of("account_authority_outbox_events", "account_authority_outbox_streams")) { - image.put( - table, - dsl.fetchSingle( - "SELECT coalesce(jsonb_agg(snapshot ORDER BY snapshot::text)::text, '[]') FROM " - + "(SELECT to_jsonb(value) || jsonb_build_object('xmin',value.xmin::text) AS snapshot FROM " - + table - + " value WHERE outbox_stream_key = ?) retained", - stream) - .get(0, String.class)); - } - return image; - } - - private static String rows(DSLContext dsl, String table, String where) { - return dsl.fetchSingle( - "SELECT coalesce(jsonb_agg(snapshot ORDER BY snapshot::text)::text, '[]') FROM " - + "(SELECT to_jsonb(value) || jsonb_build_object('xmin',value.xmin::text) AS snapshot FROM " - + table - + " value" - + where - + ") retained") - .get(0, String.class); - } - - private record FailedHosting( - IssuedAccount issued, Fixture hosting, Input input, String failureImage) {} -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java deleted file mode 100644 index 17e160a886..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java +++ /dev/null @@ -1,478 +0,0 @@ -package net.firedevops.firemud.accountservice.client; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.stripe.exception.StripeException; -import com.stripe.model.StripeObject; -import com.stripe.net.ApiMode; -import com.stripe.net.ApiResource.RequestMethod; -import com.stripe.net.BaseAddress; -import com.stripe.net.RequestOptions; -import com.stripe.net.StripeResponseGetter; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.accountservice.repository.AccountHostingPlanQuote; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreationRecord; -import org.junit.jupiter.api.Test; - -/** Real SDK transport proof with explicitly controlled private owner-dispatch inputs. */ -class StripeHostingSubscriptionProvisionerTest { - private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); - private static final UUID ACCOUNT = UUID.randomUUID(); - private static final UUID CUSTOMER_OPERATION = UUID.randomUUID(); - private static final UUID CUSTOMER_KEY = UUID.randomUUID(); - private static final UUID OPERATION = UUID.randomUUID(); - private static final UUID SUBSCRIPTION = UUID.randomUUID(); - private static final AccountSubscriptionCreationRecord CREATION = - new AccountSubscriptionCreationRecord( - UUID.randomUUID(), - "sha256:" + "a".repeat(64), - SUBSCRIPTION, - UUID.randomUUID(), - new OwnerFence(ACCOUNT, 1, UUID.randomUUID()), - "hosting", - new AccountHostingPlanQuote("hosting", "price_exact", 2, 10, 1, 100), - UUID.randomUUID(), - 1, - CUSTOMER_OPERATION, - "cus_exact", - OPERATION, - UUID.randomUUID(), - "pending", - 1, - NOW.minusSeconds(1)); - - @Test - void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() { - Transport transport = transport(search(""), subscription(), subscription()); - var located = - (StripeHostingSubscriptionProvisioner.Located) adapter(transport).provision(dispatch(true)); - assertThat(located.providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(located.observation().providerQuantity()).isEqualTo(2); - assertThat(transport.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions", - "/v1/subscriptions/sub_exact"); - assertThat(transport.methods) - .containsExactly( - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.POST, - RequestMethod.GET); - assertThat(transport.options) - .extracting(RequestOptions::getIdempotencyKey) - .containsExactly(null, null, null, OPERATION.toString(), null); - assertThat(transport.options) - .allSatisfy( - options -> { - assertThat(options.getConnectTimeout()).isEqualTo(250); - assertThat(options.getReadTimeout()).isEqualTo(1000); - assertThat(options.getMaxNetworkRetries()).isZero(); - }); - assertThat(transport.params.get(3)) - .containsOnlyKeys( - "customer", - "default_payment_method", - "items", - "metadata", - "collection_method", - "payment_behavior"); - assertThat(transport.params.get(3)) - .containsEntry("customer", "cus_exact") - .containsEntry("default_payment_method", "pm_exact") - .containsEntry("collection_method", "charge_automatically") - .containsEntry("payment_behavior", "default_incomplete"); - assertThat(StripeHostingSubscriptionProvisioner.Located.class.getConstructors()).isEmpty(); - } - - @Test - void unknownOrExpiredIdempotencyOutcomeNeverAuthorizesAnotherCreate() { - Transport missing = transport(search(""), subscriptionList()); - assertThat(adapter(missing).provision(dispatch(false))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); - assertThat(missing.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions"); - assertThat(missing.methods) - .containsExactly( - RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); - assertThat(missing.params.get(3)) - .containsEntry("customer", "cus_exact") - .containsEntry("status", "all") - .containsEntry("limit", 100L); - Transport lost = transport(search(""), subscription()); - lost.failureAt = 3; - lost.failure = mock(StripeException.class); - assertThat(adapter(lost).provision(dispatch(true))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "PROVIDER_OUTCOME_UNKNOWN", lost.failure)); - assertThat(lost.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions"); - assertThat(lost.methods) - .containsExactly( - RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.POST); - Transport recovered = transport(search(subscription()), subscription()); - assertThat(adapter(recovered).provision(dispatch(false))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Located.class); - assertThat(recovered.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions/sub_exact"); - assertThat(recovered.methods) - .containsExactly( - RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); - } - - @Test - void emptySearchUsesBoundedCustomerListOnlyForNonInitialLookup() { - Transport recovered = transport(search(""), subscriptionList(subscription()), subscription()); - var located = - (StripeHostingSubscriptionProvisioner.Located) - adapter(recovered).provision(dispatch(false)); - assertThat(located.providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(recovered.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions", - "/v1/subscriptions/sub_exact"); - assertThat(recovered.methods) - .containsExactly( - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.GET); - assertThat(recovered.params.get(3)) - .containsEntry("customer", "cus_exact") - .containsEntry("status", "all") - .containsEntry("limit", 100L); - - Transport incomplete = transport(search(""), subscriptionList(true, subscription())); - assertThat(adapter(incomplete).provision(dispatch(false))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); - assertThat(incomplete.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions"); - - Transport ambiguous = - transport(search(""), subscriptionList(subscription() + "," + subscription())); - assertThat(adapter(ambiguous).provision(dispatch(false))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); - assertThat(ambiguous.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions"); - - Transport wrongCustomer = - transport(search(""), subscriptionList(subscription().replace("cus_exact", "cus_other"))); - assertThat(adapter(wrongCustomer).provision(dispatch(false))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); - Transport wrongMetadata = - transport( - search(""), - subscriptionList( - subscription().replace(OPERATION.toString(), UUID.randomUUID().toString()))); - assertThat(adapter(wrongMetadata).provision(dispatch(false))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); - } - - @Test - void searchFailureDuplicatesAndIndependentBindingMismatchRemainNonterminal() { - Transport failed = transport(search("")); - failed.failureAt = 2; - failed.failure = mock(StripeException.class); - assertThat(adapter(failed).provision(dispatch(true))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "PROVIDER_OUTCOME_UNKNOWN", failed.failure)); - assertThat(failed.paths) - .containsExactly( - "/v1/customers/cus_exact", "/v1/payment_methods/pm_exact", "/v1/subscriptions/search"); - assertThat(failed.methods) - .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); - Transport duplicate = transport(search(subscription() + "," + subscription())); - assertThat(adapter(duplicate).provision(dispatch(true))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_SEARCH", null)); - assertThat(duplicate.paths) - .containsExactly( - "/v1/customers/cus_exact", "/v1/payment_methods/pm_exact", "/v1/subscriptions/search"); - assertThat(duplicate.methods) - .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); - Transport mismatch = - transport(search(subscription()), subscription().replace("pm_exact", "pm_wrong")); - assertThat(adapter(mismatch).provision(dispatch(false))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "INDEPENDENT_PROVIDER_READBACK_UNRESOLVED", null)); - assertThat(mismatch.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions/sub_exact"); - assertThat(mismatch.methods) - .containsExactly( - RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); - } - - @Test - void incompleteFirstInvoiceRemainsNonAuthorizingWithoutAnyPaymentConfirmationCall() { - String incomplete = - subscription().replace("\"status\":\"active\"", "\"status\":\"incomplete\""); - Transport transport = transport(search(""), incomplete, incomplete); - var located = - (StripeHostingSubscriptionProvisioner.Located) adapter(transport).provision(dispatch(true)); - assertThat(located.observation().providerStatus()).isEqualTo("incomplete"); - var policy = - new AccountHostingSubscriptionLifecyclePolicy( - Duration.ofSeconds(30), - new RecoveryTiming(Duration.ofMinutes(1), Duration.ofMinutes(1))); - var decision = policy.evaluate(located.observation(), NOW, null); - assertThat(decision.resolved()).isFalse(); - assertThat(decision.reason()) - .isEqualTo(AccountHostingSubscriptionLifecyclePolicy.Reason.UNMAPPED_PROVIDER_STATUS); - assertThat(transport.params.get(3)).containsEntry("payment_behavior", "default_incomplete"); - assertThat(transport.paths) - .containsExactly( - "/v1/customers/cus_exact", - "/v1/payment_methods/pm_exact", - "/v1/subscriptions/search", - "/v1/subscriptions", - "/v1/subscriptions/sub_exact"); - assertThat(transport.methods) - .containsExactly( - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.GET, - RequestMethod.POST, - RequestMethod.GET); - } - - @Test - void uncommittedDispatchAndExpiredLeaseRefuseBeforeSdkIo() { - Transport transport = new Transport(); - ProviderDispatch uncommitted = dispatch(true); - when(uncommitted.readyForProviderIo()).thenReturn(false); - assertThatThrownBy(() -> adapter(transport).provision(uncommitted)) - .hasMessageContaining("independent"); - var expired = - new StripeHostingSubscriptionProvisioner( - new com.stripe.StripeClient(transport), - Clock.fixed(NOW.plusSeconds(20), ZoneOffset.UTC), - false, - Duration.ofMillis(250), - Duration.ofSeconds(1)); - assertThat(expired.provision(dispatch(true))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_LEASE_EXPIRED", null)); - assertThat(transport.paths).isEmpty(); - assertThat(transport.methods).isEmpty(); - } - - @Test - void mismatchedProviderInstrumentAndAmbientTransactionCannotReachCreate() { - Transport detached = transport(search("")); - // The controlled PaymentMethod now names another Customer: no search/create follows. - var responses = new ArrayList<>(detached.responses); - responses.set(1, responses.get(1).replace("cus_exact", "cus_other")); - Transport mismatch = new Transport(responses.toArray(String[]::new)); - assertThat(adapter(mismatch).provision(dispatch(true))) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending( - "PROVIDER_PREREQUISITES_UNRESOLVED", null)); - assertThat(mismatch.paths) - .containsExactly("/v1/customers/cus_exact", "/v1/payment_methods/pm_exact"); - assertThat(mismatch.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); - Transport ambient = new Transport(); - org.springframework.transaction.support.TransactionSynchronizationManager - .setActualTransactionActive(true); - try { - assertThatThrownBy(() -> adapter(ambient).provision(dispatch(true))) - .hasMessageContaining("ambient SQL"); - assertThat(ambient.paths).isEmpty(); - assertThat(ambient.methods).isEmpty(); - } finally { - org.springframework.transaction.support.TransactionSynchronizationManager - .setActualTransactionActive(false); - } - } - - private static ProviderDispatch dispatch(boolean initial) { - var claim = mock(ProvisioningClaim.class); - when(claim.creation()).thenReturn(CREATION); - when(claim.claimedAt()).thenReturn(NOW.minusSeconds(1)); - when(claim.expiresAt()).thenReturn(NOW.plusSeconds(10)); - var dispatch = mock(ProviderDispatch.class); - when(dispatch.claim()).thenReturn(claim); - when(dispatch.providerPaymentMethodId()).thenReturn("pm_exact"); - when(dispatch.customerProviderIdempotencyId()).thenReturn(CUSTOMER_KEY); - when(dispatch.readyForProviderIo()).thenReturn(true); - when(dispatch.initialCallAllowed()).thenReturn(initial); - when(dispatch.expectedBinding("sub_exact")) - .thenReturn( - new StripeHostingSubscriptionObserver.ExpectedBinding( - "sub_exact", - SUBSCRIPTION, - "cus_exact", - "pm_exact", - "price_exact", - 2, - StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, - OPERATION, - false)); - return dispatch; - } - - private static StripeHostingSubscriptionProvisioner adapter(Transport transport) { - return new StripeHostingSubscriptionProvisioner( - new com.stripe.StripeClient(transport), - Clock.fixed(NOW, ZoneOffset.UTC), - false, - Duration.ofMillis(250), - Duration.ofSeconds(1)); - } - - private static Transport transport(String... responses) { - var all = new ArrayList(); - all.add( - "{\"object\":\"customer\",\"id\":\"cus_exact\",\"livemode\":false,\"deleted\":false,\"metadata\":{" - + "\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"customer_provisioning\"," - + "\"firemud_operation_id\":\"" - + CUSTOMER_OPERATION - + "\",\"firemud_account_id\":\"" - + ACCOUNT - + "\"}}"); - all.add( - "{\"object\":\"payment_method\",\"id\":\"pm_exact\",\"customer\":\"cus_exact\",\"livemode\":false," - + "\"type\":\"card\",\"card\":{\"brand\":\"visa\",\"last4\":\"4242\",\"exp_month\":12,\"exp_year\":2030}}"); - all.addAll(List.of(responses)); - return new Transport(all.toArray(String[]::new)); - } - - private static String search(String objects) { - return "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" + objects + "]}"; - } - - private static String subscriptionList(String... objects) { - return subscriptionList(false, objects); - } - - private static String subscriptionList(boolean hasMore, String... objects) { - return "{\"object\":\"list\",\"has_more\":" - + hasMore - + ",\"data\":[" - + String.join(",", objects) - + "]}"; - } - - private static String subscription() { - return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"cus_exact\",\"default_payment_method\":\"pm_exact\"," - + "\"livemode\":false,\"status\":\"active\",\"cancel_at_period_end\":false,\"metadata\":{" - + "\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"subscription_provisioning\"," - + "\"firemud_operation_id\":\"" - + OPERATION - + "\",\"firemud_subscription_id\":\"" - + SUBSCRIPTION - + "\"}," - + "\"items\":{\"has_more\":false,\"data\":[{\"id\":\"si_exact\",\"object\":\"subscription_item\",\"subscription\":\"sub_exact\"," - + "\"quantity\":2,\"current_period_start\":1793577500,\"current_period_end\":1793578500,\"price\":{\"id\":\"price_exact\",\"object\":\"price\"}}]}}"; - } - - private static final class Transport implements StripeResponseGetter { - private final List responses; - private final List paths = new ArrayList<>(); - private final List methods = new ArrayList<>(); - private final List> params = new ArrayList<>(); - private final List options = new ArrayList<>(); - private int failureAt = -1; - private StripeException failure; - - private Transport(String... responses) { - this.responses = List.of(responses); - } - - @Override - @SuppressWarnings("unchecked") - public T request( - BaseAddress base, - RequestMethod method, - String path, - Map parameters, - Type type, - RequestOptions requestOptions, - ApiMode mode) - throws StripeException { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - int index = paths.size(); - paths.add(path); - methods.add(method); - params.add(parameters == null ? Map.of() : Map.copyOf(parameters)); - options.add(requestOptions); - if (index == failureAt) { - throw failure; - } - return (T) com.stripe.net.ApiResource.GSON.fromJson(responses.get(index), type); - } - - @Override - public InputStream requestStream( - BaseAddress base, - RequestMethod method, - String path, - Map parameters, - RequestOptions options, - ApiMode mode) { - throw new AssertionError("No streaming"); - } - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 41c8f08db3..3d6f9cb464 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -72,7 +72,6 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( long secondsAfterExpiry) { Instant expiresAt = Instant.parse("2026-11-07T00:00:10Z"); UUID requestId = UUID.randomUUID(); - UUID subscriptionId = UUID.randomUUID(); UUID attemptId = UUID.randomUUID(); var controlledIntents = mock(AccountSubscriptionIntentRepository.class); var controlledRepository = @@ -89,58 +88,28 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( false); var creation = mock(AccountSubscriptionCreationRecord.class); when(creation.requestId()).thenReturn(requestId); - when(creation.subscriptionId()).thenReturn(subscriptionId); - when(controlledIntents.findCreation(requestId)).thenReturn(Optional.of(creation)); - var current = mock(AccountSubscriptionCurrentRecord.class); - when(current.subscriptionId()).thenReturn(subscriptionId); - when(current.rowVersion()).thenReturn(7L); - when(controlledIntents.lockForProvisioningSettlement(requestId, 7L)).thenReturn(current); var claim = mock(ProvisioningClaim.class); when(claim.creation()).thenReturn(creation); when(claim.attemptId()).thenReturn(attemptId); - when(claim.attemptNumber()).thenReturn(2); when(claim.subscriptionRowVersion()).thenReturn(7L); when(claim.claimedAt()).thenReturn(expiresAt.minusSeconds(10)); when(claim.expiresAt()).thenReturn(expiresAt); var retainedWork = mock(Record.class); when(retainedWork.get("last_attempt_id", UUID.class)).thenReturn(attemptId); - when(retainedWork.get("last_attempt_id")).thenReturn(attemptId); - when(retainedWork.get("subscription_id", UUID.class)).thenReturn(subscriptionId); - when(retainedWork.get("subscription_row_version", Long.class)).thenReturn(7L); when(retainedWork.get("phase", String.class)).thenReturn("CLAIMED"); when(retainedWork.get("deadline_at", OffsetDateTime.class)) .thenReturn(expiresAt.plusSeconds(3590).atOffset(ZoneOffset.UTC)); String lockedWorkSql = "SELECT * FROM subscription_provisioning_work WHERE request_id = ? FOR UPDATE"; when(dsl.fetchOne(lockedWorkSql, requestId)).thenReturn(retainedWork); - String linksSql = - "SELECT lifecycle_inflight_request_id, current_receipt_request_id " - + "FROM subscription WHERE subscription_id = ?"; - var links = mock(Record.class); - when(dsl.fetchOne(linksSql, subscriptionId)).thenReturn(links); - String retainedAttemptSql = - "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?"; - var retainedAttempt = mock(Record.class); - when(retainedAttempt.get("request_id", UUID.class)).thenReturn(requestId); - when(retainedAttempt.get("subscription_id", UUID.class)).thenReturn(subscriptionId); - when(retainedAttempt.get("attempt_number", Integer.class)).thenReturn(2); - when(retainedAttempt.get("claimed_row_version", Long.class)).thenReturn(7L); - when(retainedAttempt.get("claimed_at", OffsetDateTime.class)) - .thenReturn(expiresAt.minusSeconds(10).atOffset(ZoneOffset.UTC)); - when(retainedAttempt.get("expires_at", OffsetDateTime.class)) - .thenReturn(expiresAt.atOffset(ZoneOffset.UTC)); - when(dsl.fetchOne(retainedAttemptSql, attemptId)).thenReturn(retainedAttempt); TransactionSynchronizationManager.setActualTransactionActive(true); assertThat(controlledRepository.deferUnresolved(claim)).isEqualTo(Disposition.ATTEMPT_EXPIRED); - // Only the exact local owner/work locks, retained attempt and lifecycle ownership reads are - // allowed: no SQL writes, reservation release, or replacement attempt occur on this return. - verify(controlledIntents).lockForProvisioningSettlement(requestId, 7L); - verify(controlledIntents).findCreation(requestId); + // Exactly the owner/retained-work locks are allowed: no SQL writes, intent settlement, + // reservation release, or replacement attempt can occur on this return. + verify(controlledIntents).lockForProvisioningRecovery(requestId, 7L); verify(dsl).fetchOne(lockedWorkSql, requestId); - verify(dsl).fetchOne(linksSql, subscriptionId); - verify(dsl).fetchOne(retainedAttemptSql, attemptId); verifyNoMoreInteractions(controlledIntents, dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java deleted file mode 100644 index 32590851fa..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java +++ /dev/null @@ -1,199 +0,0 @@ -package net.firedevops.firemud.accountservice.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import java.util.UUID; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -import org.springframework.transaction.support.DefaultTransactionStatus; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -class AccountHostingSubscriptionProvisioningServiceTest { - private final AccountHostingSubscriptionLifecycleRepository repository = - mock(AccountHostingSubscriptionLifecycleRepository.class); - private final StripeHostingSubscriptionProvisioner provider = - mock(StripeHostingSubscriptionProvisioner.class); - private final AccountHostingSubscriptionLifecycleService lifecycle = - mock(AccountHostingSubscriptionLifecycleService.class); - private final LocalTransactions transactions = new LocalTransactions(); - private final AccountHostingSubscriptionProvisioningService service = - new AccountHostingSubscriptionProvisioningService( - repository, provider, lifecycle, transactions); - private final ProvisioningClaim claim = mock(ProvisioningClaim.class); - - @AfterEach - void clearAmbient() { - TransactionSynchronizationManager.setActualTransactionActive(false); - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clearSynchronization(); - } - } - - @Test - void claimCommitAndIndependentReadbackPrecedeProviderAndUnknownOutcomeDefersWithoutLifecycle() { - ProviderDispatch prepared = mock(ProviderDispatch.class); - ProviderDispatch readback = mock(ProviderDispatch.class); - when(readback.claim()).thenReturn(claim); - when(repository.prepareProviderDispatch(any(), any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return prepared; - }); - when(repository.readProviderDispatch(prepared)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(transactions.commits).isEqualTo(1); - return readback; - }); - when(provider.provision(readback)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(transactions.commits).isEqualTo(2); - return new StripeHostingSubscriptionProvisioner.Pending("UNKNOWN", null); - }); - when(repository.deferUnresolved(claim)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return Disposition.WAITING; - }); - var result = - (AccountHostingSubscriptionProvisioningService.Pending) - service.provision(claim, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.disposition()).isEqualTo(Disposition.WAITING); - assertThat(transactions.commits).isEqualTo(3); - verifyNoInteractions(lifecycle); - } - - @ParameterizedTest - @ValueSource(strings = {"DISPATCH_LEASE_EXPIRED", "PROVIDER_OUTCOME_UNKNOWN"}) - void expiredAttemptReturnsTypedPendingWithoutStartingLifecycle(String providerReason) { - ProviderDispatch prepared = mock(ProviderDispatch.class); - ProviderDispatch readback = mock(ProviderDispatch.class); - when(readback.claim()).thenReturn(claim); - when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); - when(repository.readProviderDispatch(prepared)).thenReturn(readback); - var providerResult = new StripeHostingSubscriptionProvisioner.Pending(providerReason, null); - when(provider.provision(readback)).thenReturn(providerResult); - when(repository.deferUnresolved(claim)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return Disposition.ATTEMPT_EXPIRED; - }); - - assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .isEqualTo( - new AccountHostingSubscriptionProvisioningService.Pending( - Disposition.ATTEMPT_EXPIRED, providerResult)); - assertThat(transactions.commits).isEqualTo(3); - verifyNoInteractions(lifecycle); - } - - @ParameterizedTest - @ValueSource(booleans = {false, true}) - void refusedDispatchCommitsLocalDeferralWithoutCallingProvider(boolean readbackRefused) { - ProviderDispatch prepared = mock(ProviderDispatch.class); - if (readbackRefused) { - when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); - when(repository.readProviderDispatch(prepared)) - .thenThrow(new FenceRejectedException("wallet observation advanced")); - } else { - when(repository.prepareProviderDispatch(any(), any())) - .thenThrow(new FenceRejectedException("wallet observation advanced")); - } - when(repository.deferUnresolved(claim)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return Disposition.TERMINAL_FAILURE; - }); - - assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .isEqualTo( - new AccountHostingSubscriptionProvisioningService.Pending( - Disposition.TERMINAL_FAILURE, - new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null))); - assertThat(transactions.commits).isEqualTo(readbackRefused ? 2 : 1); - verify(repository).deferUnresolved(claim); - verifyNoInteractions(provider, lifecycle); - } - - @Test - void refusedDispatchCannotHideStaleClaimSettlementFailure() { - when(repository.prepareProviderDispatch(any(), any())) - .thenThrow(new FenceRejectedException("dispatch refused")); - when(repository.deferUnresolved(claim)) - .thenThrow(new FenceRejectedException("stale retained attempt")); - - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .isInstanceOf(FenceRejectedException.class) - .hasMessage("stale retained attempt"); - assertThat(transactions.commits).isZero(); - verifyNoInteractions(provider, lifecycle); - } - - @Test - void failedIndependentReadbackNeverCallsProvider() { - ProviderDispatch prepared = mock(ProviderDispatch.class); - when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); - when(repository.readProviderDispatch(prepared)) - .thenThrow(new IllegalStateException("readback rejected")); - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .hasMessageContaining("readback rejected"); - assertThat(transactions.commits).isEqualTo(1); - verifyNoInteractions(provider, lifecycle); - } - - @Test - void ambientTransactionAndSynchronizationRefuseBeforeAnyEffects() { - TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .hasMessageContaining("ambient SQL"); - TransactionSynchronizationManager.setActualTransactionActive(false); - TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .hasMessageContaining("ambient SQL"); - verifyNoInteractions(repository, provider, lifecycle); - } - - private static final class LocalTransactions extends AbstractPlatformTransactionManager { - private int commits; - - @Override - protected Object doGetTransaction() { - return new Object(); - } - - @Override - protected void doBegin(Object transaction, TransactionDefinition definition) {} - - @Override - protected void doCommit(DefaultTransactionStatus status) { - commits++; - } - - @Override - protected void doRollback(DefaultTransactionStatus status) {} - } -} diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 359dea0f2b..bf39db3a85 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -18,12 +18,8 @@ import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; class AccountRuntimeStubServerCompatibilityTest { - private static final String TENANT_ID = "5c03483e-d14c-4dc4-806e-297cdd209612"; - private static final String GAME_INSTANCE_ID = "fceab4e7-2922-4e6f-a4f4-dbaab3e25875"; private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; private static final String NAMESPACE_ID = "2ea958e0-13a2-41d0-9c39-59a96cf31412"; private static final Set NON_RUNTIME_METHODS = @@ -69,7 +65,6 @@ void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { assertField(descriptor, "membership_version", 6, FieldDescriptor.Type.UINT64); assertField(descriptor, "membership_authority_generation", 7, FieldDescriptor.Type.UINT64); - assertField(descriptor, "gameplay_admission_allowed", 10, FieldDescriptor.Type.BOOL); } @Test @@ -103,10 +98,10 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(accountUuid) - .setTenantId(TENANT_ID) + .setTenantId("11") .setRealmId(REALM_ID) - .setGameInstanceId(GAME_INSTANCE_ID) - .setSessionId("1") + .setGameInstanceId("33") + .setSessionId("session-1") .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") .setRequestId("join-request-1") @@ -115,13 +110,13 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe stub.issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId(TENANT_ID) + .setTenantId("11") .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") - .setGameInstanceId(GAME_INSTANCE_ID) + .setGameInstanceId("33") .setCatalogRevision(1L) .setPointerVersion(1L) .build()); @@ -186,18 +181,6 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro .setPlayerContext( validRequest.getPlayerContext().toBuilder().setRequestId(" ")) .build(), - validRequest.toBuilder() - .setPlayableStateScope("PRIVATE") - .setPlayerContext( - validRequest.getPlayerContext().toBuilder() - .setPlayableStateScope("PRIVATE")) - .build(), - validRequest.toBuilder().setWorldSlug("w".repeat(129)).build(), - validRequest.toBuilder().setRealmSlug("r".repeat(129)).build(), - validRequest.toBuilder() - .setPlayerContext( - validRequest.getPlayerContext().toBuilder().setRequestId("r".repeat(129))) - .build(), validRequest.toBuilder().setCatalogRevision(0L).build(), validRequest.toBuilder().setPointerVersion(-1L).build()); @@ -212,148 +195,8 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro } } - @ParameterizedTest - @ValueSource( - strings = { - "11", "00000000-0000-0000-0000-000000000000", - "5C03483E-D14C-4DC4-806E-297CDD209612", "1-1-1-1-1" - }) - void directTextScopeAndJoinRejectNoncanonicalTargetIds(String invalidId) throws Exception { - try (var server = new AccountRuntimeStubServer(0)) { - server.mapAccountId("demo@example.com", 7L); - String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); - var channel = - ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); - try { - var stub = AccountServiceGrpc.newBlockingStub(channel); - var request = validConnectScopeRequest(accountUuid); - var caller = request.getPlayerContext(); - var invalidRequests = - List.of( - request.toBuilder() - .setTenantId(invalidId) - .setPlayerContext(caller.toBuilder().setTenantId(invalidId)) - .build(), - request.toBuilder() - .setRealmId(invalidId) - .setPlayerContext(caller.toBuilder().setRealmId(invalidId)) - .build(), - request.toBuilder() - .setGameInstanceId(invalidId) - .setPlayerContext(caller.toBuilder().setGameInstanceId(invalidId)) - .build(), - request.toBuilder() - .setPlayableStateNamespaceId(invalidId) - .setPlayerContext(caller.toBuilder().setPlayableStateNamespaceId(invalidId)) - .build()); - var join = - JoinPublicProductionMembershipRequest.newBuilder() - .setPlayerContext(caller) - .setConnectScopeId(stub.issueDirectTextConnectScope(request).getConnectScopeId()) - .setRequestId(caller.getRequestId()) - .build(); - assertThat(stub.joinPublicProductionMembership(join).getSuccess()).isTrue(); - for (var invalidRequest : invalidRequests) { - var scope = stub.issueDirectTextConnectScope(invalidRequest); - assertThat(scope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(scope.getConnectScopeId()).isEmpty(); - var replay = - stub.joinPublicProductionMembership( - join.toBuilder().setPlayerContext(invalidRequest.getPlayerContext()).build()); - assertThat(replay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(replay.getSuccess()).isFalse(); - assertThat(replay.getReplayed()).isFalse(); - } - } finally { - channel.shutdownNow(); - } - } - } - - @ParameterizedTest - @ValueSource( - strings = { - "", - " ", - "session-1", - "0", - "-1", - "+1", - "1.0", - "9223372036854775808", - "00000000000000000000000000000000100" - }) - void directTextScopeAndJoinRejectInvalidTransportSessionsBeforeReplay(String session) - throws Exception { - try (var server = new AccountRuntimeStubServer(0)) { - server.mapAccountId("demo@example.com", 7L); - var channel = - ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); - try { - var stub = AccountServiceGrpc.newBlockingStub(channel); - var request = - validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); - var invalidCaller = request.getPlayerContext().toBuilder().setSessionId(session).build(); - var invalidScope = - stub.issueDirectTextConnectScope( - request.toBuilder().setPlayerContext(invalidCaller).build()); - assertThat(invalidScope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(invalidScope.getConnectScopeId()).isEmpty(); - var join = - JoinPublicProductionMembershipRequest.newBuilder() - .setPlayerContext(request.getPlayerContext()) - .setConnectScopeId(stub.issueDirectTextConnectScope(request).getConnectScopeId()) - .setRequestId(request.getPlayerContext().getRequestId()) - .build(); - var invalidJoin = join.toBuilder().setPlayerContext(invalidCaller).build(); - assertThat(stub.joinPublicProductionMembership(invalidJoin).getError().getCode()) - .isEqualTo("INVALID_ARGUMENT"); - assertThat(stub.joinPublicProductionMembership(join).getSuccess()).isTrue(); - var replay = stub.joinPublicProductionMembership(invalidJoin); - assertThat(replay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(replay.getSuccess()).isFalse(); - assertThat(replay.getReplayed()).isFalse(); - } finally { - channel.shutdownNow(); - } - } - } - - @ParameterizedTest - @ValueSource(strings = {"1", "0001", "9223372036854775807", "00000000000000000000000000000001"}) - void directTextScopeAndJoinAcceptAccountTransportSessionRange(String session) throws Exception { - try (var server = new AccountRuntimeStubServer(0)) { - server.mapAccountId("demo@example.com", 7L); - var channel = - ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); - try { - var stub = AccountServiceGrpc.newBlockingStub(channel); - var request = - validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); - request = - request.toBuilder() - .setPlayerContext(request.getPlayerContext().toBuilder().setSessionId(session)) - .build(); - var scope = stub.issueDirectTextConnectScope(request); - assertThat(scope.getError().getCode()).isEmpty(); - var join = - stub.joinPublicProductionMembership( - JoinPublicProductionMembershipRequest.newBuilder() - .setPlayerContext(request.getPlayerContext()) - .setConnectScopeId(scope.getConnectScopeId()) - .setRequestId(request.getPlayerContext().getRequestId()) - .build()); - assertThat(join.getSuccess()).isTrue(); - assertThat(join.getTenantId()).isEqualTo(TENANT_ID); - } finally { - channel.shutdownNow(); - } - } - } - @Test - void joinRequiresCallerSessionBeforeReplayAndResetClearsRetainedScopesAndOutcomes() - throws Exception { + void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { server.mapAccountId("demo@example.com", 7L); String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); @@ -371,44 +214,20 @@ void joinRequiresCallerSessionBeforeReplayAndResetClearsRetainedScopesAndOutcome .setRequestId("join-request-1") .build(); - var blankSessionRequest = - validJoin.toBuilder() - .setPlayerContext(validJoin.getPlayerContext().toBuilder().setSessionId(" ")) - .build(); - var blankSession = stub.joinPublicProductionMembership(blankSessionRequest); + var blankSession = + stub.joinPublicProductionMembership( + validJoin.toBuilder() + .setPlayerContext(validJoin.getPlayerContext().toBuilder().setSessionId(" ")) + .build()); assertThat(blankSession.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(blankSession.getSuccess()).isFalse(); assertThat(stub.joinPublicProductionMembership(validJoin).getSuccess()).isTrue(); - for (var invalidRequest : - List.of( - blankSessionRequest, - validJoin.toBuilder().setConnectScopeId("missing-scope").build(), - validJoin.toBuilder() - .setPlayerContext( - validJoin.getPlayerContext().toBuilder() - .setRealmId("a87e157e-d63b-4bac-ad7c-2bd51c7ad81c")) - .build())) { - var invalidReplay = stub.joinPublicProductionMembership(invalidRequest); - assertThat(invalidReplay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(invalidReplay.getSuccess()).isFalse(); - assertThat(invalidReplay.getReplayed()).isFalse(); - } server.resetRuntimeState(); var afterReset = stub.joinPublicProductionMembership(validJoin); assertThat(afterReset.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(afterReset.getSuccess()).isFalse(); - - String freshScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); - assertThat(freshScopeId).isNotEqualTo(connectScopeId); - var freshJoin = - stub.joinPublicProductionMembership( - validJoin.toBuilder().setConnectScopeId(freshScopeId).build()); - assertThat(freshJoin.getError().getCode()).isEmpty(); - assertThat(freshJoin.getSuccess()).isTrue(); - assertThat(freshJoin.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); - assertThat(freshJoin.getReplayed()).isFalse(); } finally { channel.shutdownNow(); } @@ -489,227 +308,32 @@ void directTextScopeIssuanceAndJoinRequireRegisteredAccountUuidAndKeepClockSnaps } } - @ParameterizedTest - @ValueSource(strings = {"MISSING", "INACTIVE"}) - void joinRetainsTerminalOutcomesAndNewRequestObservesActiveMembership(String lifecycle) - throws Exception { - var clock = Clock.fixed(Instant.parse("2026-10-30T12:34:56Z"), ZoneOffset.UTC); - try (var server = new AccountRuntimeStubServer(0, clock)) { - server.mapAccountId("demo@example.com", 7L); - long previousVersion = "MISSING".equals(lifecycle) ? 1L : 3L; - if ("MISSING".equals(lifecycle)) server.setMembershipExists(false); - else server.setMembershipInactive(); - server.setMembershipVersion(previousVersion); - server.setAllowPublicJoin(false); - String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); - var scopeRequest = validConnectScopeRequest(accountUuid); - var channel = - ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); - try { - var stub = AccountServiceGrpc.newBlockingStub(channel); - var scope = stub.issueDirectTextConnectScope(scopeRequest); - var request = - JoinPublicProductionMembershipRequest.newBuilder() - .setPlayerContext(scopeRequest.getPlayerContext()) - .setConnectScopeId(scope.getConnectScopeId()) - .setRequestId("join-request-1") - .build(); - var before = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); - var denied = stub.joinPublicProductionMembership(request); - assertThat(denied.getSuccess()).isFalse(); - assertThat(denied.getOutcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); - assertThat(denied.getReplayed()).isFalse(); - assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) - .isEqualTo(before); - - server.setAllowPublicJoin(true); - var deniedReplay = stub.joinPublicProductionMembership(request); - assertThat(deniedReplay).isEqualTo(denied.toBuilder().setReplayed(true).build()); - assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) - .isEqualTo(before); - - var nextRequest = withRequestId(request, "join-request-2"); - var joined = stub.joinPublicProductionMembership(nextRequest); - assertThat(joined.getSuccess()).isTrue(); - assertThat(joined.getOutcomeCode()).isEqualTo("JOINED"); - assertThat(joined.getReplayed()).isFalse(); - assertThat(joined.getMembershipVersion()).isEqualTo(previousVersion + 1L); - assertThat(joined.getGameplayAdmissionAllowed()).isTrue(); - var after = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); - assertThat(after.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); - assertThat(after.getMembershipLifecycleState()).isEqualTo("ACTIVE"); - - server.setAllowPublicJoin(false); - var repeated = stub.joinPublicProductionMembership(nextRequest); - assertThat(repeated).isEqualTo(joined.toBuilder().setReplayed(true).build()); - assertThat(stub.joinPublicProductionMembership(request)) - .isEqualTo(denied.toBuilder().setReplayed(true).build()); - var alreadyActive = - stub.joinPublicProductionMembership(withRequestId(request, "join-request-3")); - assertThat(alreadyActive.getSuccess()).isTrue(); - assertThat(alreadyActive.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); - assertThat(alreadyActive.getReplayed()).isFalse(); - assertThat(alreadyActive.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); - assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) - .isEqualTo(after); - - server.denyGameplayAdmission(); - var nonAdmittingReplay = - joined.toBuilder().setReplayed(true).setGameplayAdmissionAllowed(false).build(); - assertThat(stub.joinPublicProductionMembership(nextRequest)).isEqualTo(nonAdmittingReplay); - server.allowGameplayAdmission(); - server.setMembershipInactive(); - assertThat(stub.joinPublicProductionMembership(nextRequest)).isEqualTo(nonAdmittingReplay); - assertThat(stub.joinPublicProductionMembership(request)) - .isEqualTo(denied.toBuilder().setReplayed(true).build()); - } finally { - channel.shutdownNow(); - } - } - } - - @Test - void retainedJoinRejectsConflictingCallerAndScopeIdentity() throws Exception { - try (var server = new AccountRuntimeStubServer(0)) { - server.mapAccountId("demo@example.com", 7L); - server.mapAccountId("other@example.com", 9L); - String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); - var scopeRequest = validConnectScopeRequest(accountUuid); - var channel = - ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); - try { - var stub = AccountServiceGrpc.newBlockingStub(channel); - var request = - JoinPublicProductionMembershipRequest.newBuilder() - .setPlayerContext(scopeRequest.getPlayerContext()) - .setConnectScopeId( - stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId()) - .setRequestId("join-request-1") - .build(); - var original = stub.joinPublicProductionMembership(request); - assertThat(original.getSuccess()).isTrue(); - var otherAccountScope = - validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(9L)); - var otherTenantScope = - scopeRequest.toBuilder() - .setTenantId("024c8a59-d3ee-4f64-8276-c4c43a2efe7f") - .setPlayerContext( - scopeRequest.getPlayerContext().toBuilder() - .setTenantId("024c8a59-d3ee-4f64-8276-c4c43a2efe7f")) - .build(); - var sameScopeNewId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); - var conflicts = - List.of( - request.toBuilder() - .setPlayerContext(request.getPlayerContext().toBuilder().setSessionId("2")) - .build(), - request.toBuilder().setConnectScopeId(sameScopeNewId).build(), - request.toBuilder() - .setPlayerContext(otherAccountScope.getPlayerContext()) - .setConnectScopeId( - stub.issueDirectTextConnectScope(otherAccountScope).getConnectScopeId()) - .build(), - request.toBuilder() - .setPlayerContext(otherTenantScope.getPlayerContext()) - .setConnectScopeId( - stub.issueDirectTextConnectScope(otherTenantScope).getConnectScopeId()) - .build()); - - for (var conflict : conflicts) { - var rejected = stub.joinPublicProductionMembership(conflict); - assertThat(rejected.getError().getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); - assertThat(rejected.getSuccess()).isFalse(); - assertThat(rejected.getReplayed()).isFalse(); - assertThat(rejected.getAccountId()).isEmpty(); - assertThat(rejected.getTenantId()).isEmpty(); - } - assertThat(stub.joinPublicProductionMembership(request)) - .isEqualTo(original.toBuilder().setReplayed(true).build()); - } finally { - channel.shutdownNow(); - } - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void alreadyActiveNonAdmittingJoinReturnsMembershipReceiptWithoutGrantingAdmission( - boolean allowPublicJoin) throws Exception { - try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { - server.mapAccountId("demo@example.com", 7L); - server.denyGameplayAdmission(); - server.setAllowPublicJoin(allowPublicJoin); - String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); - var scopeRequest = validConnectScopeRequest(accountUuid); - ManagedChannel channel = - ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); - try { - AccountServiceGrpc.AccountServiceBlockingStub stub = - AccountServiceGrpc.newBlockingStub(channel); - String connectScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); - var before = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); - var reply = - stub.joinPublicProductionMembership( - JoinPublicProductionMembershipRequest.newBuilder() - .setPlayerContext(scopeRequest.getPlayerContext()) - .setConnectScopeId(connectScopeId) - .setRequestId("join-request-1") - .build()); - - assertThat(reply.getSuccess()).isTrue(); - assertThat(reply.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); - assertThat(reply.getGameplayAdmissionAllowed()).isFalse(); - assertThat(reply.getMembershipVersion()).isEqualTo(before.getMembershipVersion()); - assertThat(reply.getMembershipAuthorityGeneration()) - .isEqualTo(before.getMembershipAuthorityGeneration()); - assertThat(reply.getMembershipId()).matches("[1-9][0-9]{0,18}"); - var after = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); - assertThat(after.getMembershipExists()).isEqualTo(before.getMembershipExists()); - assertThat(after.getGameplayAdmissionAllowed()) - .isEqualTo(before.getGameplayAdmissionAllowed()); - assertThat(after.getMembershipVersion()).isEqualTo(before.getMembershipVersion()); - assertThat(after.getMembershipAuthorityGeneration()) - .isEqualTo(before.getMembershipAuthorityGeneration()); - } finally { - channel.shutdownNow(); - } - } - } - private static IssueDirectTextConnectScopeRequest validConnectScopeRequest(String accountUuid) { PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(accountUuid) - .setTenantId(TENANT_ID) + .setTenantId("11") .setRealmId(REALM_ID) - .setGameInstanceId(GAME_INSTANCE_ID) - .setSessionId("1") + .setGameInstanceId("33") + .setSessionId("session-1") .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") .setRequestId("join-request-1") .build(); return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId(TENANT_ID) + .setTenantId("11") .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") - .setGameInstanceId(GAME_INSTANCE_ID) + .setGameInstanceId("33") .setCatalogRevision(1L) .setPointerVersion(1L) .build(); } - private static JoinPublicProductionMembershipRequest withRequestId( - JoinPublicProductionMembershipRequest request, String requestId) { - return request.toBuilder() - .setRequestId(requestId) - .setPlayerContext(request.getPlayerContext().toBuilder().setRequestId(requestId)) - .build(); - } - private static void assertField( Descriptor descriptor, String name, int number, FieldDescriptor.Type type) { FieldDescriptor field = descriptor.findFieldByName(name); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 4a80b18323..7a132094fa 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -41,9 +41,7 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; -/** - * Shared test-only Account runtime fake; its responses establish no canonical runtime authority. - */ +/** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { private static final Set IMPLEMENTED_RUNTIME_METHODS = @@ -72,7 +70,6 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final Map accountIdsByUuid = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); private final Map connectScopesById = new ConcurrentHashMap<>(); - private final Map joinOutcomesByRequestId = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { this(port, Clock.systemUTC()); @@ -169,7 +166,7 @@ public void setRealmAccessGranted(boolean granted) { realmAccessGranted.set(granted); } - public synchronized void resetRuntimeState() { + public void resetRuntimeState() { authenticateRequests.clear(); membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); @@ -184,7 +181,6 @@ public synchronized void resetRuntimeState() { .values() .forEach(id -> accountIdsByUuid.put(accountUuidForTestFixture(id), id)); connectScopesById.clear(); - joinOutcomesByRequestId.clear(); } @Override @@ -269,11 +265,27 @@ public void issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); - if (!isValidDirectTextCaller(caller) - || !isBoundedText(request.getWorldSlug(), 128) - || !isBoundedText(request.getRealmSlug(), 128) + if (caller.getAccountId().isBlank() + || resolveRegisteredAccountId(caller.getAccountId()) == null + || caller.getTenantId().isBlank() + || caller.getRealmId().isBlank() + || caller.getRequestId().isBlank() + || caller.getGameInstanceId().isBlank() + || caller.getPlayableStateNamespaceId().isBlank() + || caller.getPlayableStateScope().isBlank() + || request.getTenantId().isBlank() + || request.getRealmId().isBlank() + || request.getGameInstanceId().isBlank() + || request.getWorldSlug().isBlank() + || request.getRealmSlug().isBlank() + || request.getPlayableStateNamespaceId().isBlank() + || request.getPlayableStateScope().isBlank() || request.getCatalogRevision() <= 0 || request.getPointerVersion() <= 0 + || !isCanonicalUuid(caller.getRealmId()) + || !isCanonicalUuid(request.getRealmId()) + || !isCanonicalUuid(caller.getPlayableStateNamespaceId()) + || !isCanonicalUuid(request.getPlayableStateNamespaceId()) || !caller.getTenantId().equals(request.getTenantId()) || !caller.getRealmId().equals(request.getRealmId()) || !caller.getGameInstanceId().equals(request.getGameInstanceId()) @@ -315,49 +327,25 @@ private static boolean isCanonicalUuid(String value) { return false; } try { - UUID parsed = UUID.fromString(value); - return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); + return UUID.fromString(value).toString().equals(value); } catch (IllegalArgumentException ex) { return false; } } - private boolean isValidDirectTextCaller(PlayerExecutionContext caller) { - return resolveRegisteredAccountId(caller.getAccountId()) != null - && isCanonicalUuid(caller.getTenantId()) - && isCanonicalUuid(caller.getRealmId()) - && isCanonicalUuid(caller.getGameInstanceId()) - && isCanonicalUuid(caller.getPlayableStateNamespaceId()) - && Set.of("SHARED", "ISOLATED").contains(caller.getPlayableStateScope()) - && isPositiveTransportSession(caller.getSessionId()) - && isBoundedText(caller.getRequestId(), 128); - } - - private static boolean isPositiveTransportSession(String value) { - if (value.length() > 32 || !value.matches("[0-9]+")) { - return false; - } - try { - return Long.parseLong(value) > 0; - } catch (NumberFormatException ex) { - return false; - } - } - - private static boolean isBoundedText(String value, int maximumLength) { - return !value.isBlank() && value.length() <= maximumLength; - } - @Override - public synchronized void joinPublicProductionMembership( + public void joinPublicProductionMembership( JoinPublicProductionMembershipRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); StubConnectScope scope = connectScopesById.get(request.getConnectScopeId()); - if (!isBoundedText(request.getConnectScopeId(), 2048) - || !isBoundedText(request.getRequestId(), 128) + if (request.getConnectScopeId().isBlank() + || request.getRequestId().isBlank() || !request.getRequestId().equals(caller.getRequestId()) - || !isValidDirectTextCaller(caller) + || caller.getAccountId().isBlank() + || resolveRegisteredAccountId(caller.getAccountId()) == null + || caller.getTenantId().isBlank() + || caller.getSessionId().isBlank() || scope == null || !scope.expiresAt().isAfter(clock.instant()) || !scope.accountId().equals(caller.getAccountId()) @@ -373,68 +361,29 @@ public synchronized void joinPublicProductionMembership( .setCode("INVALID_ARGUMENT") .setMessage("Direct-text JOIN request is incomplete")) .build()); - } else { - StubJoinOutcome retained = joinOutcomesByRequestId.get(request.getRequestId()); - if (retained != null) { - if (retained.request().equals(request)) { - var replay = retained.response().toBuilder().setReplayed(true); - if (retained.response().getSuccess()) { - // A retained membership receipt never preserves historical admission permission. - replay.setGameplayAdmissionAllowed( - "ACTIVE".equals(membershipLifecycleState.get()) && gameplayAdmissionAllowed.get()); - } - responseObserver.onNext(replay.build()); - } else { - responseObserver.onNext( - JoinPublicProductionMembershipResponse.newBuilder() - .setError( - ErrorDetail.newBuilder() - .setCode("IDEMPOTENCY_CONFLICT") - .setMessage("Direct-text JOIN request ID conflicts")) - .build()); - } - } else { - JoinPublicProductionMembershipResponse response = evaluateJoin(caller); - joinOutcomesByRequestId.put(request.getRequestId(), new StubJoinOutcome(request, response)); - responseObserver.onNext(response); - } - } - responseObserver.onCompleted(); - } - - private JoinPublicProductionMembershipResponse evaluateJoin(PlayerExecutionContext caller) { - if ("ACTIVE".equals(membershipLifecycleState.get())) { - return JoinPublicProductionMembershipResponse.newBuilder() - .setSuccess(true) - .setOutcomeCode("ALREADY_ACTIVE") - .setAccountId(caller.getAccountId()) - .setTenantId(caller.getTenantId()) - .setMembershipId("1") - .setMembershipVersion(membershipVersion.get()) - .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) - .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) - .build(); } else if (!allowPublicJoin.get()) { - return JoinPublicProductionMembershipResponse.newBuilder() - .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") - .setAccountId(caller.getAccountId()) - .setTenantId(caller.getTenantId()) - .build(); + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .build()); } else { - long joinedMembershipVersion = membershipVersion.incrementAndGet(); membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); - return JoinPublicProductionMembershipResponse.newBuilder() - .setSuccess(true) - .setOutcomeCode("JOINED") - .setAccountId(caller.getAccountId()) - .setTenantId(caller.getTenantId()) - .setMembershipId("1") - .setMembershipVersion(joinedMembershipVersion) - .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) - .setGameplayAdmissionAllowed(true) - .build(); + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId( + "stub-membership-" + caller.getAccountId() + "-" + caller.getTenantId()) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .build()); } + responseObserver.onCompleted(); } @Override @@ -538,8 +487,4 @@ private record StubConnectScope( String playableStateNamespaceId, String playableStateScope, Instant expiresAt) {} - - private record StubJoinOutcome( - JoinPublicProductionMembershipRequest request, - JoinPublicProductionMembershipResponse response) {} } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 7f4e0d1c26..bf74dc929e 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -7,7 +7,6 @@ import com.google.protobuf.Empty; import com.google.protobuf.util.JsonFormat; -import com.zaxxer.hikari.HikariDataSource; import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; import io.grpc.BindableService; import io.grpc.CallOptions; @@ -305,9 +304,7 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @Container static final PostgreSQLContainer ACCOUNT = - // Account's exact-original LOGIN disposal refuses nondurable PostgreSQL settings. - new PostgreSQLContainer<>(TestContainerImages.postgres()) - .withCommand("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer REDIS = @@ -586,9 +583,6 @@ private void compose( "Created placement proof requires the committed coupled owner path"); } UUID tenant = UUID.randomUUID(); - var sharedAuthoredSource = controlledSource("controlled-upstream", tenant); - var sharedCreation = - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sharedAuthoredSource); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT.getJdbcUrl(), @@ -597,22 +591,12 @@ private void compose( REDIS.getHost(), REDIS.getMappedPort(6379), proofDirectory.resolve("account"), - sharedCreation, - true); + tenant); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( account, proofDirectory.resolve("issuer"), NAMESPACE); - var accountDurability = - issuer - .sourceDsl() - .fetchSingle( - "SELECT pg_is_in_recovery() AS recovery, current_setting('fsync') AS fsync," - + " current_setting('synchronous_commit') AS commit_mode"); - assertThat(accountDurability.get("recovery", Boolean.class)).isFalse(); - assertThat(accountDurability.get("fsync", String.class)).isEqualTo("on"); - assertThat(accountDurability.get("commit_mode", String.class)).isEqualTo("on"); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) @@ -696,14 +680,7 @@ public void attachAccountRedemptionProjection( var createdPublication = new AtomicReference(); var preparedInput = preparationInputs( - world, - gs, - tuple, - claim.get(), - tenant, - playerCreatedPlacement, - createdPublication, - sharedAuthoredSource); + world, gs, tuple, claim.get(), tenant, playerCreatedPlacement, createdPublication); var input = refusal == Refusal.MISMATCHED_ATTEMPT ? new WorldCanonicalInstancePreparation.Input( @@ -1881,7 +1858,6 @@ public void close() {} exerciseCoupledCanonicalInitialAdmission( gs, world, - account, issuer, currentAttempt, proofDirectory, @@ -2360,9 +2336,7 @@ private static javax.sql.DataSource dataSource(DSLContext dsl) { var provider = (org.jooq.impl.DataSourceConnectionProvider) dsl.configuration().connectionProvider(); var proxy = (TransactionAwareDataSourceProxy) provider.dataSource(); - var target = Objects.requireNonNull(proxy.getTargetDataSource()); - // Concurrency/fence probes retain independent physical connections outside the owner pool. - return target instanceof HikariDataSource pool ? pool.getDataSource() : target; + return Objects.requireNonNull(proxy.getTargetDataSource()); } private static SQLException findSqlException(Throwable failure) { @@ -2448,7 +2422,6 @@ private static String prefixedSha256(byte[] bytes) { private static void exerciseCoupledCanonicalInitialAdmission( Database gs, Database world, - AccountControlUiOriginalOrderFixture account, AccountOriginalStartSessionAuthorizationProofFixture issuer, GrpcOriginalStartSessionCurrentAttemptClient currentAttempt, Path proofDirectory, @@ -3031,7 +3004,6 @@ private static void exerciseCoupledCanonicalInitialAdmission( composeActualEntityWorldRegionPrerequisite( gs, world, - account, proofDirectory, pki, factory, @@ -3112,7 +3084,6 @@ private static void assertAccountAdmissionProtectionSettled( private static void composeActualEntityWorldRegionPrerequisite( Database gs, Database world, - AccountControlUiOriginalOrderFixture account, Path proofDirectory, WorldOriginalStartSessionPreparationProofPki worldPki, GrpcChannelFactory channels, @@ -3461,8 +3432,6 @@ private static void composeActualEntityWorldRegionPrerequisite( try { var worldEndpoints = new ServiceEndpointsProperties(); worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); - // The earlier generic password-write proof deliberately leaves creator LOGIN - // currentness unavailable. The later composition uses a separate fresh player. var initialLocationClient = new CanonicalInitialPlayerLocationClient( worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); @@ -3569,18 +3538,6 @@ private static void composeActualEntityWorldRegionPrerequisite( assertThat(regionProofs.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); assertThat(regionProofs.expiredGrantRejectedWithoutStateChange()).isTrue(); } - // Run the genuine second-player DEMO mutation after original placement assertions. - WorldPublishedAdmissionSourceComposition.exercise( - proofDirectory, - gs.dsl(), - gs.manager(), - REDIS.getHost(), - REDIS.getMappedPort(6379), - currentTarget, - accountUuid, - account, - worldEndpoints, - worldPki.client("game-session-service")); } finally { shutdown(worldLocationServer); entityReceiptClient.close(); @@ -4200,11 +4157,11 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, UUID tenant, boolean playerCreatedPlacement, - AtomicReference createdPublication, - AuthoredWorldSourceEvidence source) + AtomicReference createdPublication) throws Exception { var intakeRepository = new WorldAuthoredSourceIntakeRepository(world.dsl()); var versionRepository = new WorldAuthoredVersionIdentityRepository(world.dsl()); + var source = controlledSource("controlled-upstream", tenant); var intake = Objects.requireNonNull( world @@ -4814,73 +4771,47 @@ private static Database database(PostgreSQLContainer postgres, String service .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); } - HikariDataSource pool = null; - try { - migrations.load().migrate(); - if ("world-management-service".equals(service) || "game-session-service".equals(service)) { - pool = new HikariDataSource(); - pool.setPoolName("world-fixture-" + schema); - pool.setDataSource(source); - pool.setMaximumPoolSize(4); - pool.setMinimumIdle(0); - } - javax.sql.DataSource ownerSource = pool == null ? source : pool; - var manager = new DataSourceTransactionManager(ownerSource); - var write = new TransactionTemplate(manager); - write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - var dsl = DSL.using(new TransactionAwareDataSourceProxy(ownerSource), SQLDialect.POSTGRES); - WorldRuntimeInstallationRegistry installation = null; - if ("world-management-service".equals(service)) { - // This is a stipulated one-workload installation solely for this receiving-owner proof. - // Real Account/GS/mTLS behavior remains exercised independently; none supplies global - // installed membership, deployment completeness or production source custody. - byte[] artifact = controlledInstallationArtifact(schema); - installation = - new WorldRuntimeInstallationRegistry( - dsl, - manager, - schema, - NAMESPACE, - () -> - new WorldRuntimeInstallationRegistry.HeldInstallation() { - private boolean closed; + migrations.load().migrate(); + var manager = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(manager); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + WorldRuntimeInstallationRegistry installation = null; + if ("world-management-service".equals(service)) { + // This is a stipulated one-workload installation solely for this receiving-owner proof. + // Real Account/GS/mTLS behavior remains exercised independently; none supplies global + // installed membership, deployment completeness or production source custody. + byte[] artifact = controlledInstallationArtifact(schema); + installation = + new WorldRuntimeInstallationRegistry( + dsl, + manager, + schema, + NAMESPACE, + () -> + new WorldRuntimeInstallationRegistry.HeldInstallation() { + private boolean closed; - @Override - public byte[] exactArtifactBytes() { - return artifact.clone(); - } + @Override + public byte[] exactArtifactBytes() { + return artifact.clone(); + } - @Override - public void requireCurrent() { - if (closed) - throw new IllegalStateException("Synthetic installation hold is closed"); - } + @Override + public void requireCurrent() { + if (closed) + throw new IllegalStateException("Synthetic installation hold is closed"); + } - @Override - public void close() { - closed = true; - } - }); - installation.register(); - } - return new Database(schema, dsl, manager, write, installation, pool); - } catch (RuntimeException | Error failure) { - try { - DSL.using(source, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } catch (RuntimeException | Error cleanupFailure) { - failure.addSuppressed(cleanupFailure); - } - if (pool != null) { - try { - pool.close(); - } catch (RuntimeException | Error cleanupFailure) { - failure.addSuppressed(cleanupFailure); - } - } - throw failure; + @Override + public void close() { + closed = true; + } + }); + installation.register(); } + return new Database(schema, dsl, manager, write, installation); } private static WorldRuntimeInstallationRegistry.Registration advanceInstallationRegistry( @@ -4980,14 +4911,11 @@ private record Database( DSLContext dsl, DataSourceTransactionManager manager, TransactionTemplate write, - WorldRuntimeInstallationRegistry installationRegistry, - HikariDataSource pool) + WorldRuntimeInstallationRegistry installationRegistry) implements AutoCloseable { @Override public void close() { - try (HikariDataSource ownedPool = pool) { - dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } + dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java deleted file mode 100644 index de8d567853..0000000000 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ /dev/null @@ -1,272 +0,0 @@ -package net.firedevops.firemud.worldmanagement.tenant; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import java.net.InetSocketAddress; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Clock; -import java.time.Duration; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; -import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; -import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; -import net.firedevops.firemud.accountservice.service.session.AccountPlayerAdmissionSharedEntitlementFixture; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; -import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; -import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; -import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; -import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginPhysicalCompositionFixture; -import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; - -/** - * Actual LOGIN and PLAYER_ADMISSION producer/consumer with a genuine absent player and shared - * Account/GS/World sources and physical GS journal/PENDING/INSTALLED state, followed by actual - * first JOIN, positive source read and known-token retirement. DEMO policy, caller coordinates, - * PKI, reset/promotion qualification and receiving custody remain controlled. No public ingress, - * protected receiving custody, World hold across JOIN, runtime activation or PLAY is proved. - */ -final class WorldPlayerAdmissionEntitlementComposition { - private WorldPlayerAdmissionEntitlementComposition() {} - - static void exercise( - Path root, - AccountControlUiOriginalOrderFixture original, - CanonicalGameplayAdmissionDecisionReadClient targets, - CanonicalPlayableTarget target, - org.jooq.DSLContext gs, - org.springframework.transaction.PlatformTransactionManager gsTransactions, - String redisHost, - int redisPort) - throws Exception { - var clock = Clock.systemUTC(); - String namespace = target.targetNamespace(); - Path directory = Files.createDirectories(root.resolve("player-admission")); - var pki = - LoopbackMtlsTestPki.create( - directory, - "Controlled genuine player admission sources", - new LoopbackMtlsTestPki.IdentitySpec( - "gs", "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", false), - new LoopbackMtlsTestPki.IdentitySpec( - "account", "spiffe://firemud/ns/" + namespace + "/sa/account-service", true)); - var creation = original.creationEvidence(); - var demo = - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - creation.canonicalTenantId(), - creation.creationRequestId(), - creation.requestDigest(), - null, - null, - null, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)); - var fixture = - new AccountPlayerAdmissionSharedEntitlementFixture( - original, directory, targets, demo, clock); - var loginOwner = fixture.login(); - var keys = pki.keyManagerFactory(pki.identity("account")); - var trust = pki.trustManagerFactory(); - Server loginServer = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer(keys)) - .trustManager(trust) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService( - ServerInterceptors.intercept( - loginOwner.authenticateReceiver(namespace), new GrpcPeerIdentityInterceptor())) - .build() - .start(); - try { - Server entitlementServer = - fixture.receiver().createUnregisteredServer("127.0.0.1:0", keys, trust); - entitlementServer.start(); - try { - var loginEndpoints = new ServiceEndpointsProperties(); - loginEndpoints.setAccountService("localhost:" + loginServer.getPort()); - var entitlementEndpoints = new ServiceEndpointsProperties(); - entitlementEndpoints.setAccountService("localhost:" + entitlementServer.getPort()); - var tls = pki.clientProperties(directory, pki.identity("gs")); - var channels = new GrpcChannelFactory(); - var source = fixture.trustedJwksSource(); - var verifier = - new AccountAsymmetricJwtVerifier( - new AccountPublicJwksCache( - source, source.sourceIdentity(), clock, Duration.ofSeconds(30)), - clock); - try (var loginClient = - new CanonicalGameplayLoginAccountClient( - loginEndpoints, - tls, - channels, - BlockingGrpcStubCustomizer.noop(), - namespace, - clock, - Duration.ofSeconds(15), - verifier); - var entitlementClient = - new AccountPlayerAdmissionEntitlementClient( - entitlementEndpoints, tls, channels, namespace, clock)) { - loginClient.initialize(); - entitlementClient.init(); - // This request is only a controlled credential source. GS allocates real coordinates. - var credentialSource = - loginOwner.loginRequest( - UUID.randomUUID(), - new GameplayCredentialSourceContext( - UUID.randomUUID(), "192.0.2.42", "trusted_tcp_proxy")); - try (var physicalLogin = - InitialGameplayLoginPhysicalCompositionFixture.open( - gs, - gsTransactions, - redisHost, - redisPort, - loginClient, - credentialSource.email(), - "192.0.2.42", - credentialSource.credential().toCharArray())) { - var login = physicalLogin.loginResult(); - var evidence = login.evidence(); - loginOwner.assertCommittedNonAdmittingLogin( - evidence.requestId(), - evidence.callerContextId(), - evidence.tokenJti(), - evidence.tokenSha256(), - evidence.expiresAtEpochSecond()); - var transport = new ObservedDirectTextTransport("1", UUID.randomUUID()); - var realmScope = - fixture.issueScopeWithControlledGameSessionCaller( - new DirectTextCallerContext( - evidence.accountId(), - target.canonicalTenantId(), - target.realmId(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - transport.transportSessionId(), - UUID.randomUUID().toString()), - new DirectTextJoinTarget( - target.canonicalTenantId(), - target.realmId(), - target.worldSlug(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion())); - var scope = realmScope.scope(); - var issued = - DirectTextIssuedConnectScope.fromAccountResponse( - evidence.accountId().toString(), - DirectTextAuthenticatedLobbyScope.targetFor(target), - IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId(scope.connectScopeId()) - .setEvaluatedAt(scope.evaluatedAt()) - .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) - .build(), - clock); - var coordinates = physicalLogin.coordinates(); - // Physical INSTALLED readback is real; protected receiving custody remains controlled. - var lobby = - new DirectTextAuthenticatedLobbyScope( - UUID.randomUUID(), - physicalLogin.installedReadback(), - transport, - target, - issued); - var received = - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); - fixture.assertNonAdmittingEvidence(received); - assertThat(received.fields()).containsEntry("variant", "PLAYER_ADMISSION"); - // Actual Account owner transition; caller binding is controlled and no World hold - // spans this JOIN transaction. Reuse only the still-current verified LOGIN result. - fixture.commitFirstJoin( - realmScope, UUID.randomUUID().toString(), transport.transportSessionId()); - var joined = - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); - fixture.assertAdmittingEvidence(joined); - var journal = new InitialGameplayLoginCoordinationJournalRepository(gs); - var beforeCustodyRefusal = journal.readCommitted(coordinates).orElseThrow(); - assertThatThrownBy( - () -> - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) - .isExactlyInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.CANCELLED); - assertThat(status.getDescription()) - .isEqualTo("Account player-admission entitlement read did not complete"); - }); - fixture.assertAdmittingEvidence(joined); - assertThat(login.evidence()).isEqualTo(evidence); - assertThat(journal.readCommitted(coordinates)).contains(beforeCustodyRefusal); - assertThat(physicalLogin.abandonOriginalAfterCustodyLoss().status()) - .isEqualTo( - net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner - .Status.ACCOUNT_RETIRED); - var beforeClosedResultRefusal = journal.readCommitted(coordinates).orElseThrow(); - // Cleanup has closed the private result. This proves local disposal refusal, - // not an Account-side retired-token read over the wire. - assertThatThrownBy( - () -> - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) - .isExactlyInstanceOf(IllegalStateException.class) - .hasMessage("Canonical LOGIN private result is closed"); - fixture.assertAdmittingEvidence(joined); - assertThat(login.evidence()).isEqualTo(evidence); - assertThat(journal.readCommitted(coordinates)).contains(beforeClosedResultRefusal); - } catch (RuntimeException | Error failure) { - failure.addSuppressed( - new AssertionError( - "Account LOGIN owner stages: " + loginOwner.ownerObservations())); - throw failure; - } - } - } finally { - stop(entitlementServer); - } - } finally { - stop(loginServer); - } - } - - private static void stop(Server server) throws InterruptedException { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } -} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java deleted file mode 100644 index 836920793e..0000000000 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package net.firedevops.firemud.worldmanagement.tenant; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.grpc.Server; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -class WorldPublishedAdmissionSourceCleanupTest { - @Test - void successfulBodyStopsServerAndChecksLatePeerDiagnostic() throws Exception { - var server = stoppedServer(); - var peer = new AtomicReference(); - Throwable result = - catchThrowable( - () -> { - try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); - var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { - peer.set("wrong authenticated peer"); - } - }); - - assertThat(result) - .isInstanceOf(AssertionError.class) - .hasMessageContaining("wrong authenticated peer"); - verify(server).shutdownNow(); - verify(server).awaitTermination(5, TimeUnit.SECONDS); - } - - @Test - void primaryFailureRetainsPeerDiagnostic() throws Exception { - var server = stoppedServer(); - var primary = new AssertionError("admission failed"); - Throwable result = run(server, "wrong authenticated peer", primary); - - assertThat(result).isSameAs(primary); - assertThat(result.getSuppressed()).hasSize(1); - assertThat(result.getSuppressed()[0]) - .isInstanceOf(AssertionError.class) - .hasMessageContaining("published policy source peer") - .hasMessageContaining("wrong authenticated peer"); - } - - @Test - void primaryFailureRetainsCleanupFailureAndPeerDiagnostic() throws Exception { - var server = stoppedServer(); - var cleanup = new InterruptedException("cleanup interrupted"); - when(server.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(cleanup); - var primary = new AssertionError("admission failed"); - Throwable result = run(server, "wrong authenticated peer", primary); - - assertThat(result).isSameAs(primary); - assertThat(result.getSuppressed()).hasSize(2); - assertThat(result.getSuppressed()[0]).isSameAs(cleanup); - assertThat(result.getSuppressed()[1]).hasMessageContaining("wrong authenticated peer"); - } - - @Test - void cleanupFailureRemainsPrimaryWhenBodySucceeds() throws Exception { - var server = stoppedServer(); - var cleanup = new IllegalStateException("shutdown failed"); - when(server.shutdownNow()).thenThrow(cleanup); - Throwable result = run(server, "wrong authenticated peer", null); - - assertThat(result).isSameAs(cleanup); - assertThat(result.getSuppressed()).hasSize(1); - assertThat(result.getSuppressed()[0]).hasMessageContaining("wrong authenticated peer"); - } - - @Test - void unsuccessfulTerminationCannotReplacePrimaryFailure() throws Exception { - var server = stoppedServer(); - when(server.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); - var primary = new AssertionError("admission failed"); - Throwable result = run(server, null, primary); - - assertThat(result).isSameAs(primary); - assertThat(result.getSuppressed()).singleElement().isInstanceOf(AssertionError.class); - } - - @Test - void successfulBodyAndCleanupDoNotFail() throws Exception { - var server = stoppedServer(); - assertThat(run(server, null, null)).isNull(); - verify(server).shutdownNow(); - verify(server).awaitTermination(5, TimeUnit.SECONDS); - } - - private static Server stoppedServer() throws InterruptedException { - var server = mock(Server.class); - when(server.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); - return server; - } - - private static Throwable run(Server server, String peerFailure, AssertionError primary) { - var peer = new AtomicReference<>(peerFailure); - return catchThrowable( - () -> { - try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); - var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { - if (primary != null) { - throw primary; - } - } - }); - } -} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java deleted file mode 100644 index 6d66e9b778..0000000000 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ /dev/null @@ -1,273 +0,0 @@ -package net.firedevops.firemud.worldmanagement.tenant; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.grpc.BindableService; -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import io.grpc.stub.StreamObserver; -import java.net.InetSocketAddress; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; -import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; -import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; -import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; -import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import net.firedevops.firemud.gamesession.repository.CanonicalPublishedAdmissionActualOwnerCompositionFixture; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; -import org.jooq.DSLContext; - -/** - * Real GS OPEN/current publication and World ACTIVE reads over authenticated sockets, followed by - * actual Account LOGIN, absent-player entitlement, owner-local first JOIN and positive source - * reread. Game Design publication, DEMO policy, PKI, caller coordinates and custody callbacks are - * controlled. No public ingress, World hold across JOIN, protected receiving custody or activation - * is proved. - */ -final class WorldPublishedAdmissionSourceComposition { - private WorldPublishedAdmissionSourceComposition() {} - - static void exercise( - Path root, - DSLContext gs, - org.springframework.transaction.PlatformTransactionManager gsTransactions, - String redisHost, - int redisPort, - CanonicalPlayableTarget target, - UUID account, - net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture - originalAccount, - ServiceEndpointsProperties worldEndpoints, - CommonGrpcClientProperties worldTls) - throws Exception { - assertThat(target.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); - var publication = - RealmPolicyPublishedEvidenceCodec.decode( - gs.fetchSingle( - "SELECT complete_policy_set_evidence FROM game_session_canonical_realm_catalog WHERE realm_id=?", - target.realmId()) - .get(0, byte[].class)); - String namespace = target.targetNamespace(); - Path directory = Files.createDirectories(root.resolve("published-admission-source")); - var pki = - LoopbackMtlsTestPki.create( - directory, - "Controlled published source composition", - new LoopbackMtlsTestPki.IdentitySpec( - "gs-server", peer(namespace, "game-session-service"), true), - new LoopbackMtlsTestPki.IdentitySpec( - "gs-client", peer(namespace, "game-session-service"), false), - new LoopbackMtlsTestPki.IdentitySpec( - "account", peer(namespace, "account-service"), false), - new LoopbackMtlsTestPki.IdentitySpec( - "design", peer(namespace, "game-design-service"), true)); - var policies = - new PublishedRealmEntryPolicySetEvidence( - publication.target(), - publication.versionNumber(), - publication.sourceCommitId(), - publication.sourceEpoch(), - publication.publishedReleaseBundleRef(), - publication.publishedReleaseBundleDigest(), - publication.publishWorkflowId(), - publication.manifestHash(), - publication.publicationVersionStateEpoch(), - publication.operationBytes(), - publication.captureBytes(), - publication.terminalEvidenceBytes(), - publication.policyCount(), - publication.policySetDigest(), - publication.policies().stream() - .map( - p -> - new PublishedRealmEntryPolicyEvidence( - p.policyId(), - p.source().commitId(), - p.source().revisionId(), - p.source().logicalRevisionId(), - p.source().policy(), - p.policyDigest())) - .toList()); - // This is the sole stipulated source: the exact published set already used by the real - // preparation/OPEN owners. No Game Design issuing-owner proof is claimed here. - var policySourcePeerFailure = new AtomicReference(); - var policySource = - new PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase() { - @Override - public void listPublishedRealmEntryPolicies( - ListPublishedRealmEntryPoliciesRequest request, - StreamObserver observer) { - var authenticatedPeer = GrpcPeerIdentity.current(); - String expectedPeer = peer(namespace, "game-session-service"); - if (authenticatedPeer == null || !expectedPeer.equals(authenticatedPeer.uri())) { - policySourcePeerFailure.compareAndSet( - null, - "Expected authenticated peer " - + expectedPeer - + " but was " - + (authenticatedPeer == null ? "missing" : authenticatedPeer.uri())); - } - observer.onNext( - PublishedRealmEntryPolicyReadGrpcCodec.toResponse( - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(request), policies)); - observer.onCompleted(); - } - }; - Server design = server(pki, "design", policySource); - // Reverse close order retains shutdown and peer diagnostics as suppressed failures. - try (var peerCheck = checkPeerOnClose(policySourcePeerFailure); - var designLifetime = stopOnClose(design)) { - var endpoints = new ServiceEndpointsProperties(); - endpoints.setGameDesignService("localhost:" + design.getPort()); - var channels = new GrpcChannelFactory(); - try (var policyClient = - new GameDesignPublishedRealmPolicyClient( - endpoints, - pki.clientProperties(directory, pki.identity("gs-client")), - channels, - namespace); - var worldClient = - new WorldCanonicalInstanceLifecycleClient( - worldEndpoints, worldTls, channels, namespace)) { - policyClient.init(); - worldClient.init(); - Server receiver = - server( - pki, - "gs-server", - CanonicalPublishedAdmissionActualOwnerCompositionFixture.receiver( - gs, namespace, policyClient, worldClient)); - try (var receiverLifetime = stopOnClose(receiver)) { - endpoints.setGameSessionService("localhost:" + receiver.getPort()); - try (var accountClient = - new CanonicalGameplayAdmissionDecisionReadClient( - endpoints, - pki.clientProperties(directory, pki.identity("account")), - channels, - namespace)) { - accountClient.init(); - var selector = - new RetainedTargetSelector( - UUID.randomUUID(), - account, - namespace, - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion()); - var resolved = accountClient.resolvePublishedRealmAdmissionTarget(selector); - var read = accountClient.readPublishedRealmAdmissionOwner(resolved.strictSelector()); - assertThat(read.selector()).isEqualTo(resolved.strictSelector()); - assertThat(read.currentTarget().canonicalGameInstanceId()) - .isEqualTo(target.canonicalGameInstanceId()); - assertThat(read.sourceEvidence().admissionPointerSnapshotDigest()) - .isEqualTo(target.admissionPointerSnapshotDigest()); - assertThat(read.sourceEvidence().gameSessionOwnerProof().proofDigest()) - .isEqualTo(target.ownerProofDigest()); - assertThat(read.sourceEvidence().publishedPolicySetEvidence().canonicalBytes()) - .containsExactly(policies.canonicalBytes()); - assertThat(read.worldLifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); - assertThat(read.worldLifecycleEvidence().lifecycleEpoch()) - .isEqualTo(target.activeWorldEpoch()); - var wrong = - new RetainedTargetSelector( - UUID.randomUUID(), - account, - namespace, - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - UUID.randomUUID(), - target.catalogRevision(), - target.pointerVersion()); - assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) - .isExactlyInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Canonical Game Session admission decision is unavailable"); - }); - var afterRefusal = accountClient.resolvePublishedRealmAdmissionTarget(selector); - assertThat(afterRefusal.selector()).isEqualTo(resolved.selector()); - assertThat(afterRefusal.currentTarget()).isEqualTo(resolved.currentTarget()); - WorldPlayerAdmissionEntitlementComposition.exercise( - root, - originalAccount, - accountClient, - target, - gs, - gsTransactions, - redisHost, - redisPort); - } - } - } - } - } - - static AutoCloseable checkPeerOnClose(AtomicReference peerFailure) { - return () -> assertThat(peerFailure.get()).as("published policy source peer").isNull(); - } - - static AutoCloseable stopOnClose(Server server) { - return () -> stop(server); - } - - private static String peer(String namespace, String service) { - return "spiffe://firemud/ns/" + namespace + "/sa/" + service; - } - - private static Server server( - LoopbackMtlsTestPki.Pki pki, String identity, BindableService receiver) throws Exception { - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( - pki.keyManagerFactory(pki.identity(identity)))) - .trustManager(pki.trustManagerFactory()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) - .build() - .start(); - } - - private static void stop(Server server) throws InterruptedException { - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } -} From c7a27f09971e1471c0b25e844271f727040f466f Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 01:59:45 +1300 Subject: [PATCH 41/66] Preserve pending JOIN intent consistently on scope expiry --- .../service/impl/AccountServiceImpl.java | 6 ++- ...g_subscription_first_provider_dispatch.sql | 3 +- .../AccountApplicationIntegrationTest.java | 49 +++++++++++++++++++ ...nonicalHostingSubscriptionTestFixture.java | 2 +- .../service/impl/AccountGrpcServiceTest.java | 25 +++++----- .../service/impl/AccountServiceImplTest.java | 40 +++++++++++++++ 6 files changed, 110 insertions(+), 15 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index e110dee271..4d12dab344 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 @@ -1121,13 +1121,17 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( private void recordCanonicalJoinFailure( CanonicalJoinScopeV2 scope, String requestId, String callerBinding, String failureCode) { + // Expiry is terminal for this caller attempt, not a new durable operation outcome. The + // reader rejects the same expired scope without rewriting its retained intent; preserve + // that behavior when time crosses the boundary during provider I/O or the commit gate. + if ("CONNECT_SCOPE_INVALID".equals(failureCode)) return; joinTransactionTemplate.executeWithoutResult( status -> { lockCanonicalScopeAccount(scope); Optional found = accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; - if (List.of("CONNECT_SCOPE_MISMATCH", "CONNECT_SCOPE_INVALID").contains(failureCode)) { + if ("CONNECT_SCOPE_MISMATCH".equals(failureCode)) { accountJoinOperationRepository.finishCanonicalFailure( requestId, scope, callerBinding, failureCode); } else { diff --git a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql index 7f8581d589..177f4527d5 100644 --- a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql +++ b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql @@ -42,8 +42,9 @@ DECLARE BEGIN SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; PERFORM 1 FROM accounts WHERE account_uuid = creation.account_uuid FOR UPDATE; - SELECT * INTO STRICT instrument FROM payment_instrument WHERE instrument_uuid = creation.payment_instrument_id FOR UPDATE; + -- Match the canonical Account -> customer -> instrument acquisition order. SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = creation.account_uuid FOR UPDATE; + SELECT * INTO STRICT instrument FROM payment_instrument WHERE instrument_uuid = creation.payment_instrument_id FOR UPDATE; SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = creation.subscription_id FOR UPDATE; SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = creation.request_id FOR UPDATE; SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = NEW.first_attempt_id; 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 5f2a0aa4a5..794c7249cf 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 @@ -737,6 +737,55 @@ void publicJoinExpiredPendingScopePreservesIntentAndCannotCommitMembership() { f.assertTransitionCount(0L); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinExpiryDuringProcessingPreservesPendingIntentAndRollsBack(boolean duringProvider) { + var f = publicJoinFixture(duringProvider); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var intent = new java.util.concurrent.atomic.AtomicReference(); + Runnable expire = + () -> { + intent.set(f.operation(request).intentDigest()); + f.clock.offset = Duration.ofMinutes(3); + }; + if (duringProvider) { + f.paid.transport().duringRead(expire); + } else { + org.mockito.Mockito.doAnswer( + invocation -> { + var result = invocation.callRealMethod(); + expire.run(); + return result; + }) + .when(f.operations) + .commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(request), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + } + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(intent.get()).isNotBlank(); + assertThat(f.operation(request).intentDigest()).isEqualTo(intent.get()); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).requestDigest()).isNull(); + assertThat(f.operation(request).terminalProof()).isNull(); + assertThat(f.operation(request).lastAttemptFailureCode()).isNull(); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + var pending = f.state(request); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(request)).isEqualTo(pending); + } + @Test void publicJoinChangedCallerOrScopeCannotReplaceOriginalTerminalBytes() { var f = publicJoinFixture(false); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index bfd24c3ba5..fb911fdfbb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -394,7 +394,7 @@ public void providerStatus(String status) { } public static final class MutableClock extends Clock { - private Instant current; + private volatile Instant current; private MutableClock(Instant current) { this.current = current; 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 f2246f2eb3..90bd7f50e3 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 @@ -324,8 +324,17 @@ void verifyEmailMapsMissingSourceToSafeUnavailableAndPreservesOtherExceptions() assertEquals("INVALID_ARGUMENT", invalid.response().getError().getCode()); } - @Test - void joinPublicProductionMembershipPreservesStoredFailureOutcome() { + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_SCOPE_MISMATCH", + "CONNECT_SCOPE_INVALID", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "TENANT_BILLING_BLOCKED", + "IDEMPOTENCY_CONFLICT", + "ENTITLEMENT_UNAVAILABLE" + }) + void joinPublicProductionMembershipPreservesStoredFailureOutcome(String outcome) { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) @@ -336,15 +345,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { Mockito.any(JoinPublicProductionRequest.class))) .thenReturn( new JoinPublicProductionResult( - false, - "ENTITLEMENT_UNAVAILABLE", - ACCOUNT_UUID, - DIRECT_TENANT, - 0L, - 0L, - 0L, - false, - true)); + false, outcome, ACCOUNT_UUID, DIRECT_TENANT, 0L, 0L, 0L, false, true)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -355,7 +356,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { assertTrue(observer.completed()); assertFalse(observer.response().getSuccess()); - assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); + assertEquals(outcome, observer.response().getOutcomeCode()); assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertEquals(DIRECT_TENANT.toString(), observer.response().getTenantId()); assertEquals("0", observer.response().getMembershipId()); 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 8413cad97c..ce60a70c84 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 @@ -1310,6 +1310,46 @@ void canonicalJoinFutureOrExpiredScopeCannotReachMembershipCommit(long seconds) verifyNoInteractions(f.terminal); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalJoinExpiryAtCommitGatesDoesNotRewritePendingIntent(boolean afterCoordinator) { + var f = canonicalJoinFixture(); + var clock = org.mockito.Mockito.mock(Clock.class); + when(clock.instant()) + .thenAnswer( + invocation -> + Instant.parse(f.scope.evaluatedAt()) + .plusSeconds(!afterCoordinator || f.joined.get() ? 120 : 1)); + f.compose(clock); + + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + // This mock-level proof observes rollback invocation, not physical SQL rollback. + org.mockito.Mockito.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + if (afterCoordinator) { + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } else { + verifyNoInteractions(f.terminal); + } + } + @Test void canonicalJoinReturnsCommittedReceiptWhenScopeExpiresAfterCommit() { var f = canonicalJoinFixture(); From 39910677841e6516bc47eba5338b2a3f9af2cac7 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 02:04:21 +1300 Subject: [PATCH 42/66] Clarify expired JOIN scope preserves retained receipt state --- .../architecture/microservices/account-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 085c247868..71ac40c49a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -387,7 +387,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | | `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current default composition:** absent canonical scope consumers, Account returns `AUTH_UNAVAILABLE` before bootstrap or connect-scope validation. With consumers manually configured, `issueConnectToken` validates the bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation; the held boundary and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** With the default composition absent, the current Account receiving method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. The Gateway path remains blocked by its explicit route guard. Current status, preserved obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** With the default composition absent, the current Account receiving method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. The Gateway path remains blocked by its explicit route guard. Current status, preserved obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. This terminates the call while preserving the existing `PENDING` or terminal receipt state; it does not authorize rewriting that state or retrying with expired authority. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | From 5a6a8634e923b0b25b9620c16b5f977b9ef003f4 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 02:50:06 +1300 Subject: [PATCH 43/66] Bind JOIN policy tenant authority and preserve smoke proof diagnostics --- .github/workflows/smoke.yml | 22 +++++--- .../pr-required-gate-context-contract.sh | 33 +++++++++++ ...countMembershipAuthorityEventProducer.java | 12 +++- ...thorityEventProducerCanonicalJoinTest.java | 56 +++++++++++++++++++ 4 files changed, 115 insertions(+), 8 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 1c86ae9a4b..436bc8283a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1174,13 +1174,21 @@ jobs: } if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && matching.event === "pull_request") { - const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => - github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { - owner, repo, run_id: matching.id, attempt_number: matching.run_attempt, per_page: 100, - }) - ); - const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); - if (candidate && await verifyKnownPlayFailure(matching, candidate, currentIdentity)) { + let knownPlayVerified = false; + try { + const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => + github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { + owner, repo, run_id: matching.id, attempt_number: matching.run_attempt, per_page: 100, + }) + ); + const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); + knownPlayVerified = Boolean(candidate) && + await verifyKnownPlayFailure(matching, candidate, currentIdentity); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); + } + if (knownPlayVerified) { const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 2d14445295..776697e8f1 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3421,6 +3421,31 @@ async function verify(mutate = () => {}) { value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); } +// Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. +const failedStart = script.indexOf('if (matching.conclusion !== "success")'); +const failedEnd = script.indexOf("const latestIdentity", failedStart); +const failedBranch = script.slice(failedStart, failedEnd); +class TerminalGitHubRequestError extends Error {} +async function failedProof(stage, error) { + const warnings = [], failures = [], outputs = []; + const github = {paginate: async () => { + if (stage === "jobs") throw error; + return stage === "malformed-jobs" ? {} : [candidate]; + }}; + const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), + setOutput: (...value) => outputs.push(value)}; + const execute = new Function("matching", "repositoryName", "github", "owner", "repo", + "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", + "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", + `return (async () => { smokeGatePolling: while (true) { ${failedBranch} break; } })();`); + await execute({...source}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, + identity, (_label, call) => call(), async () => {throw error;}, async () => false, + TerminalGitHubRequestError, core); + assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); + assert.deepEqual(outputs, []); +} const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { "github.event_name": "pull_request", "github.repository": repositoryName, @@ -3438,6 +3463,14 @@ function markerAccepted(overrides = {}) { return new Function("includes", `return (${expression});`)((values, value) => values.includes(value)); } (async () => { + for (const stage of ["jobs", "proof", "malformed-jobs"]) { + await failedProof(stage, Object.assign(new Error("unavailable"), {status: 404})); + } + await failedProof("proof", null); + for (const stage of ["jobs", "proof"]) { + const terminal = new TerminalGitHubRequestError("permission denied"); + await assert.rejects(failedProof(stage, terminal), error => error === terminal); + } assert.equal(markerAccepted(), true); for (const overrides of [ {"steps.runtime-smoke.outputs.known_play_failure": ""}, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 1c29990421..0df534e287 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -323,7 +323,17 @@ public void requireCurrentCanonicalJoinPolicy( || !scope.tenantId().equals(current.scopeEvidence().tenantUuid())) { throw new IllegalStateException("Canonical JOIN policy selector changed"); } - var tenant = tenantAuthorityEventRepository.readCurrentByTenant(scope.tenantId()); + CompositeSnapshot authority = + authorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, + scope.accountId(), + List.of(scope.tenantId()), + List.of(scope.tenantId())); + var tenant = + readCurrentTenantSourceEvent( + scope.tenantId(), + current.scopeEvidence().tenantProvenance(), + only(authority.tenants(), "tenant")); if (hosting == null) { requireCurrentJoinEntitlement( current, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 181ad55ea3..bf2d16b32b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -99,6 +99,62 @@ void clearTransactionState() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "false,current", "true,current", + "false,baseline", "true,baseline", + "false,generation", "true,generation", + "false,source-version", "true,source-version", + "false,provenance", "true,provenance" + }) + void alreadyActivePolicyRequiresTenantEventBoundToCurrentAuthorityAndOperation( + boolean paid, String evidence) { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + fixture.startWritableTransaction(); + var event = + tenantAuthorityEvent( + TENANT_UUID, + "provenance".equals(evidence) ? UUID.randomUUID() : TENANT_OPERATION_ID, + "generation".equals(evidence) ? 3L : 2L, + "source-version".equals(evidence) ? 3L : 2L, + 1L, + 1L); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + // Both entitlement sources agree with the event, even when its authority or provenance is + // stale. + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(event)); + if ("baseline".equals(evidence)) { + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 1L, 1L)); + } + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(hosting.readCurrent(fence, observed)).thenReturn(paidReceipt(event, 5L, true)); + Runnable validate = + () -> + fixture.producer.requireCurrentCanonicalJoinPolicy( + fixture.scope, + fixture.operation(CALLER_BINDING), + false, + paid ? hosting : null, + paid ? fence : null, + paid ? observed : null); + + if ("current".equals(evidence)) { + validate.run(); + } else { + assertThatThrownBy(validate::run) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("tenant authority evidence"); + } + verifyNoInteractions(fixture.outbox); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + @Test void restoreRequiresCanonicalScopeBeforeReadingOwnerState() { Fixture fixture = new Fixture(); From 59efcb9130d8b6511f0620e352ab2cd42cbecf0f Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 03:00:11 +1300 Subject: [PATCH 44/66] Construct paid JOIN receipt before Mockito stubbing --- ...countMembershipAuthorityEventProducerCanonicalJoinTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index bf2d16b32b..895c108fda 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -133,7 +133,8 @@ void alreadyActivePolicyRequiresTenantEventBoundToCurrentAuthorityAndOperation( var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); var fence = mock(ReadFence.class); var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); - when(hosting.readCurrent(fence, observed)).thenReturn(paidReceipt(event, 5L, true)); + var receipt = paidReceipt(event, 5L, true); + when(hosting.readCurrent(fence, observed)).thenReturn(receipt); Runnable validate = () -> fixture.producer.requireCurrentCanonicalJoinPolicy( From e360158c84638b6f734fe432a67e3511ec06aa7f Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 03:39:49 +1300 Subject: [PATCH 45/66] Bind canonical PLAY exception to classifier content --- .github/workflows/smoke.yml | 33 ++++++---- .../pr-required-gate-context-contract.sh | 63 ++++++++++++++++--- .../gamesession/client/AccountClientTest.java | 9 ++- 3 files changed, 85 insertions(+), 20 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 436bc8283a..7906fde96c 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -609,6 +609,11 @@ jobs: // One canonical producer definition; the contract test reports fingerprint upkeep. const canonicalRuntimeWorkflowSha256 = "e337cb510a2ac861f823e62ad4e31026ab1c0734f4103f21b4d98a14c30eefb4"; + const canonicalPlayClassifierSha256 = { + "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", + "dev-tools/smoke/smoke_common.py": "a1e36948b500ac796295560cb8c22321ebe47eab78be9e1f4d58837053547534", + "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b" + }; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = `${owner}/${repo}`; @@ -840,18 +845,22 @@ jobs: (step.conclusion === "failure" && !expectedFailures.includes(step.name))) || jobs.some((other) => other.id !== job.id && (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; - // Only the current PR test merge definition can attest this exception. - const workflowSha = identity.mergeSha; - const { data: definition } = await withTransientGitHubRetry( - "immutable runtime workflow definition lookup", - () => github.rest.repos.getContent({ owner, repo, path: workflowPath, ref: workflowSha }) - ); - if (definition.type !== "file" || definition.path !== workflowPath || - definition.encoding !== "base64" || typeof definition.content !== "string") return false; - const bytes = Buffer.from(definition.content, "base64"); - if (definition.size !== bytes.length) return false; - if (require("node:crypto").createHash("sha256").update(bytes).digest("hex") !== - canonicalRuntimeWorkflowSha256) return false; + // The workflow and classifier bytes must all belong to the verified PR test merge. + for (const [path, expectedSha256] of Object.entries({ + [workflowPath]: canonicalRuntimeWorkflowSha256, + ...canonicalPlayClassifierSha256, + })) { + const { data: definition } = await withTransientGitHubRetry( + `immutable PLAY classifier definition lookup: ${path}`, + () => github.rest.repos.getContent({ owner, repo, path, ref: identity.mergeSha }) + ); + if (definition.type !== "file" || definition.path !== path || + definition.encoding !== "base64" || typeof definition.content !== "string") return false; + const bytes = Buffer.from(definition.content, "base64"); + if (definition.size !== bytes.length) return false; + if (require("node:crypto").createHash("sha256").update(bytes).digest("hex") !== + expectedSha256) return false; + } const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 776697e8f1..3155b7b26f 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -495,7 +495,9 @@ trap 'rm -rf "$tmp_dir"' EXIT smoke_clock_fixture="$tmp_dir/smoke-clock.js" python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' from pathlib import Path +import base64 import hashlib +import json import re import sys import yaml @@ -520,13 +522,37 @@ if fingerprint is None or fingerprint[1] != expected: "Smoke Gate producer fingerprint is stale: after reviewing runtime-images.yml, update " f"canonicalRuntimeWorkflowSha256 in smoke.yml to {expected} and rerun this contract." ) +classifier_paths = ( + "dev-tools/verify-smoke-images.sh", + "dev-tools/smoke/smoke_common.py", + "services/game-session-service/websocket-login-look-smoke.sh", +) +classifier_fingerprints = re.search(r"const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});", script) +if classifier_fingerprints is None: + raise SystemExit("Smoke Gate must fingerprint the canonical PLAY classifier files") +classifiers = json.loads(classifier_fingerprints[1]) +if set(classifiers) != set(classifier_paths): + raise SystemExit("Smoke Gate PLAY classifier fingerprint paths must match the three canonical files") +classifier_definitions = {} +for path in classifier_paths: + classifier_bytes = (root / path).read_bytes() + expected = hashlib.sha256(classifier_bytes).hexdigest() + if classifiers[path] != expected: + raise SystemExit( + f"Smoke Gate PLAY classifier fingerprint is stale: after reviewing {path}, update " + f"canonicalPlayClassifierSha256 in smoke.yml to {expected} for that path and rerun this contract." + ) + classifier_definitions[path] = { + "type": "file", "path": path, "encoding": "base64", + "content": base64.b64encode(classifier_bytes).decode("ascii"), "size": len(classifier_bytes), + } +Path(sys.argv[2] + ".classifiers.json").write_text(json.dumps(classifier_definitions)) producer_job = producer["jobs"]["pr-local-smoke"] cancelled_inventory = re.search( r"const preExecutionCancelledJobNames = new Set\(\[([\s\S]*?)\]\);", script ) if cancelled_inventory is None: raise SystemExit("Smoke Gate must declare its bounded pre-execution cancellation inventory") -import json producer_job_names = [job["name"] for job in producer["jobs"].values()] Path(sys.argv[2] + ".cancelled-job-names.json").write_text(json.dumps(producer_job_names)) if producer_job["name"] != "PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }})": @@ -3392,6 +3418,8 @@ const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); +const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); +const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".classifiers.json", "utf8")); const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; const run = {id: 99, run_attempt: 2, event: "pull_request"}; @@ -3409,17 +3437,27 @@ async function verify(mutate = () => {}) { const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, eventHeadRepository: repositoryName, currentPullRequest: {state: "open", head: {sha: headSha}, base: {ref: "develop"}, labels: [{name: "canonical-play-transition"}]}, - definition: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}); + definitions: {...classifierDefinitions, + [workflowPath]: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}}); mutate(data); + const contentRequests = []; const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, rest: {actions: {getWorkflow: async () => ({data: {id: 7, path: workflowPath, name: "Build Runtime Images"}}), - getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, repos: {getContent: async () => ({data: data.definition})}}}; - return new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", - "canonicalRuntimeWorkflowSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", + getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, repos: {getContent: async ({owner, repo, path, ref}) => { + assert.equal(`${owner}/${repo}`, repositoryName); + assert.equal(ref, mergeSha, "PLAY classifier attestation must use the immutable verified merge"); + contentRequests.push(path); + if (!data.definitions[path]) throw Object.assign(new Error("definition unavailable"), {status: 404}); + return {data: data.definitions[path]}; + }}}}; + const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", + "canonicalRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( - github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, + github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPlayClassifierSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); + if (accepted) assert.deepEqual(contentRequests, [workflowPath, ...Object.keys(classifierDefinitions)]); + return accepted; } // Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. const failedStart = script.indexOf('if (matching.conclusion !== "success")'); @@ -3485,6 +3523,17 @@ function markerAccepted(overrides = {}) { {"github.event_name": "workflow_run"}, ]) assert.equal(markerAccepted(overrides), false); assert.equal(await verify(), true); + for (const path of Object.keys(classifierDefinitions)) { + assert.equal(await verify(d => { + const altered = Buffer.concat([Buffer.from(d.definitions[path].content, "base64"), Buffer.from("\n# altered classifier\n")]); + d.definitions[path].content = altered.toString("base64"); + d.definitions[path].size = altered.length; + }), false, `altered classifier bytes must fail closed: ${path}`); + for (const change of [ + {type: "dir"}, {path: "other-classifier"}, {encoding: "none"}, {content: null}, {size: 0}, + ]) assert.equal(await verify(d => {Object.assign(d.definitions[path], change);}), false, `${path}: ${JSON.stringify(change)}`); + await assert.rejects(verify(d => {delete d.definitions[path];}), /definition unavailable/); + } for (const stackPr of [3405, 3409, 3407, 3408, 3410]) { assert.equal(await verify(d => {d.pr = String(stackPr); d.source.display_title = d.source.display_title.replace("pr-3390", `pr-${stackPr}`);}), true); } @@ -3506,7 +3555,7 @@ function markerAccepted(overrides = {}) { d => {d.latest.conclusion = "success"; assert.equal(d.source.conclusion, "failure");}, d => {d.source.path = ".github/workflows/spoof.yml";}, d => {d.source.repository.full_name = "attacker/FireMUD";}, - d => {d.definition.content = Buffer.from("spoof").toString("base64"); d.definition.size = 5;}, + d => {d.definitions[workflowPath].content = Buffer.from("spoof").toString("base64"); d.definitions[workflowPath].size = 5;}, d => {d.jobs.push({...d.candidate, id: 124});}, d => {d.jobs.push({id: 2, status: "completed", conclusion: "failure"});}, d => {d.jobs[0].steps.push(step("Unrelated failure", "failure"));}, 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 0653864b9c..ff8aed9ff4 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 @@ -554,7 +554,14 @@ void joinRejectsForeignOrMalformedSuccessfulIdentityWithoutRetry() throws Except .isEqualTo("AUTH_UNAVAILABLE"); } for (String tenant : - List.of("", "tenant", "0", "23", " 22", "022", "33333333-3333-4333-8333-333333333333")) { + List.of( + "", + "tenant", + "22", + "00000000-0000-0000-0000-000000000000", + "22222222-2222-4222-8222-22222222222A", + " " + directTextTarget().tenantId(), + "33333333-3333-4333-8333-333333333333")) { when(fixture.initialStub().joinPublicProductionMembership(any())) .thenReturn(success.toBuilder().setTenantId(tenant).build()); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) From 4b20594a1101fcc1fdd57ffe6385fa9a18409ab6 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 05:42:06 +1300 Subject: [PATCH 46/66] Capture bounded Account CI worker stall diagnostics --- .github/scripts/run-gradle-module-checks.sh | 10 +- .github/workflows/ci.yml | 1 + .../tests/test_gradle_compile_failure.py | 215 +++++++++++++- .../collect-gradle-compile-failure.py | 275 +++++++++++++++++- 4 files changed, 495 insertions(+), 6 deletions(-) diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 51a4be02ec..ac66965e1d 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -63,6 +63,14 @@ if [[ -z "$CHECK_LOG" ]]; then '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile fi +declare -a CAPTURE_ARGS=() +# Observe Account's stalled forks only on an isolated hosted Linux runner. +if [[ "$MODULE" == "account-service" && "$PARTITION" != "full" && + "${GITHUB_ACTIONS:-}" == true && "${RUNNER_ENVIRONMENT:-}" == github-hosted && + "${RUNNER_OS:-}" == Linux ]]; then + CAPTURE_ARGS+=(--root "$ROOT_DIR" --stall-output + "$ROOT_DIR/build/reports/gradle-stall/$MODULE/partition-$PARTITION") +fi set +e bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ @@ -72,7 +80,7 @@ bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ "${CHECK_ARGS[@]}" \ --profile --info --console=plain 2>&1 | \ ( - python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$CHECK_LOG" + python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$CHECK_LOG" "${CAPTURE_ARGS[@]}" capture_status=$? if (( capture_status != 0 )); then cat >/dev/null diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad3a195196..0389908fe9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1225,6 +1225,7 @@ jobs: path: | build/reports/profile/ build/reports/compile-failure/${{ matrix.module }}/ + build/reports/gradle-stall/${{ matrix.module }}/ if-no-files-found: warn retention-days: 14 diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 2c37ce5d85..523f00aec2 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -5,13 +5,14 @@ import json import os import shutil +import signal import subprocess import sys import tempfile import time import unittest from pathlib import Path -from unittest.mock import patch +from unittest.mock import Mock, patch ROOT = Path(__file__).resolve().parents[2] SPEC = importlib.util.spec_from_file_location( @@ -41,6 +42,218 @@ def write(self, relative, content='source'): path.write_text(content) return path + def stall_identity(self, pid=123, parent=100, role='daemon'): + return {'pid': pid, 'ppid': parent, 'start': 42, 'role': role, + 'state': 'S', 'cpu_ticks': 1, 'rss_pages': 10, 'jcmd': '/unused/jcmd'} + + def test_stall_timer_activity_attribution_and_one_batch(self): + identity = self.stall_identity() + with patch.object(CAPTURE.time, 'monotonic', return_value=0) as clock, patch.object( + CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE.subprocess, 'Popen') as launch, patch.object(CAPTURE.os, 'killpg') as kill, patch.object( + CAPTURE, 'owns_session', return_value=True): + observer = CAPTURE.StallObserver(self.root, self.output) + observer.observe(b'The client will now receive all logging from the daemon (pi') + observer.observe(b'd: 123). The daemon log file: secret') + self.assertEqual(identity, observer.daemon) + clock.return_value = 299 + observer.tick() + launch.assert_not_called() + observer.observe(b'progress') + clock.return_value = 598 + observer.tick() + launch.assert_not_called() + clock.return_value = 599 + observer.tick() + launch.assert_called_once() + self.assertTrue(launch.call_args.kwargs['start_new_session']) + self.assertEqual(subprocess.DEVNULL, launch.call_args.kwargs['stdin']) + clock.return_value = 690 + observer.tick() + kill.assert_called_once() + observer.observe(b'new progress') + clock.return_value = 1000 + observer.tick() + launch.assert_called_once() + + def test_stall_without_daemon_and_launch_failure_are_nonfatal(self): + with patch.object(CAPTURE.time, 'monotonic', side_effect=[0, 301]), patch.object( + CAPTURE.subprocess, 'Popen') as launch: + observer = CAPTURE.StallObserver(self.root, self.output) + observer.tick() + launch.assert_called_once() + self.assertIn('null', launch.call_args.args[0]) + with patch.object(CAPTURE.time, 'monotonic', side_effect=[0, 301]), patch.object( + CAPTURE.subprocess, 'Popen', side_effect=OSError('unavailable')): + observer = CAPTURE.StallObserver(self.root, self.output) + observer.daemon = self.stall_identity() + observer.tick() + self.assertTrue(observer.attempted) + self.assertIsNone(observer.child) + + def test_stall_processes_include_both_workers_exclude_unrelated_and_reused(self): + proc = self.root / 'proc' + java = self.write('jdk/bin/java') + def process(pid, parent, main, display=b''): + base = proc / str(pid) + base.mkdir(parents=True) + fields = ['0'] * 22 + fields[0], fields[1], fields[19] = 'S', str(parent), '42' + (base / 'stat').write_text(f'{pid} (java) ' + ' '.join(fields)) + (base / 'cmdline').write_bytes(b'java\0' + main + b'\0' + display + b'\0SECRET\0') + (base / 'exe').symlink_to(java) + process(100, 1, b'org.gradle.launcher.daemon.bootstrap.GradleDaemon') + for pid in (101, 102): + process(pid, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b'Gradle Test Executor 4') + process(103, 999, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b'Gradle Test Executor 5') + process(104, 100, b'other.JavaMain') + with patch.object(CAPTURE, 'PROC_ROOT', proc): + daemon = CAPTURE.java_identity(100) + selected = CAPTURE.stall_processes(daemon) + self.assertEqual({100, 101, 102}, {p['pid'] for p in selected}) + self.assertNotIn('SECRET', json.dumps(selected)) + self.assertEqual([], CAPTURE.stall_processes({**daemon, 'start': 43})) + with patch.object(CAPTURE, 'STALL_MAX_PROCESSES', 2): + self.assertEqual(2, len(CAPTURE.stall_processes(daemon))) + + def test_stall_sanitizer_rejects_names_secrets_and_diagnostic_prose(self): + raw = (b'"SECRET-password" #17 tid=0xabc nid=0xdef waiting\n' + b' java.lang.Thread.State: WAITING (parking)\n' + b' at java.base@25/java.lang.Object.wait0(Native Method)\n' + b' at org.example.Work.run(Work.java:42)\n' + b' - locked <0xabc> (a java.lang.Object)\n' + b'JAVA_TOOL_OPTIONS=SECRET\njdbc:postgresql://SECRET\n' + b'SELECT SECRET FROM private\nVM.command_line SECRET\n') + output = CAPTURE.sanitized_threads(raw) + self.assertNotIn('SECRET', output) + self.assertIn('#17 tid=0xabc nid=0xdef', output) + self.assertIn('WAITING', output) + self.assertIn('Work.run(Work.java:42)', output) + self.assertIn('locked <0xabc>', output) + + def test_stall_identity_change_never_attaches(self): + original = self.stall_identity() + with patch.object(CAPTURE, 'java_identity', return_value={**original, 'start': 43}), patch.object( + CAPTURE.subprocess, 'Popen') as launch: + result = CAPTURE.thread_snapshot(original) + self.assertEqual('exited-or-changed', result['status']) + launch.assert_not_called() + + def test_stall_fake_jcmd_output_limit_and_timeout(self): + fake = self.write('jcmd', '#!/usr/bin/env python3\n' + 'print("at org.example.Work.run(Work.java:42)", flush=True)\n' + 'print("SECRET" * 1000, flush=True)\n' + 'import time; time.sleep(10)\n') + fake.chmod(0o755) + identity = {**self.stall_identity(), 'jcmd': str(fake)} + with patch.object(CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE, 'STALL_DUMP_BYTES', 100): + result = CAPTURE.thread_snapshot(identity) + self.assertEqual('limited', result['status']) + self.assertNotIn('SECRET', json.dumps(result)) + self.assertNotIn('jcmd', result) + fake.write_text('#!/usr/bin/env python3\nimport time; time.sleep(10)\n') + with patch.object(CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE, 'STALL_COMMAND_SECONDS', 0.1): + result = CAPTURE.thread_snapshot(identity) + self.assertEqual('timeout', result['status']) + + def test_stall_missing_jcmd_is_nonfatal(self): + identity = self.stall_identity() + with patch.object(CAPTURE, 'java_identity', return_value=identity): + self.assertEqual('unavailable', CAPTURE.thread_snapshot(identity)['status']) + + def test_stall_snapshots_are_fresh_bounded_and_reject_symlinks(self): + identity = self.stall_identity() + with patch.object(CAPTURE, 'stall_processes', return_value=[identity]), patch.object( + CAPTURE, 'thread_snapshot', return_value={'status': 'complete'}), patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()): + CAPTURE.collect_stall(self.root, self.output, identity) + CAPTURE.collect_stall(self.root, self.output, identity) + self.assertEqual(4, len(list(self.output.glob('observation-*/snapshot-*.json')))) + link = self.root / 'escape' + link.symlink_to(self.output, target_is_directory=True) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(self.root, link, identity) + + def test_stall_session_guard_never_signals_parent_or_unowned_group(self): + with patch.object(CAPTURE.os, 'getpgid', return_value=50), patch.object( + CAPTURE.os, 'getsid', return_value=50): + self.assertFalse(CAPTURE.owns_session(123)) + with patch.object(CAPTURE, 'owns_session', return_value=False), patch.object( + CAPTURE.os, 'killpg') as kill: + with self.assertRaises(SystemExit): + CAPTURE.stop_stall_session(signal.SIGALRM, None) + observer = CAPTURE.StallObserver(self.root, self.output) + child = observer.child = Mock() + observer.close() + kill.assert_not_called() + child.wait.assert_not_called() + with patch.object(CAPTURE, 'owns_session', return_value=True), patch.object( + CAPTURE.os, 'killpg') as kill, self.assertRaises(SystemExit): + CAPTURE.stop_stall_session(signal.SIGALRM, None) + kill.assert_called_once_with(os.getpid(), signal.SIGKILL) + + def test_stall_capture_cancellation_closes_observer(self): + observer = Mock() + observer.tick.side_effect = SystemExit(143) + read_fd, write_fd = os.pipe() + os.close(write_fd) + with os.fdopen(read_fd, 'rb') as source, self.assertRaises(SystemExit): + list(CAPTURE.capture_chunks(source, observer)) + observer.close.assert_called_once() + + def test_stall_missing_attribution_is_explicit_and_never_enumerates_jvms(self): + with patch.object(CAPTURE, 'stall_processes') as enumerate_jvms, patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()) as output: + CAPTURE.collect_stall(self.root, self.output, None) + enumerate_jvms.assert_not_called() + self.assertIn('"daemon_attribution": "unavailable"', output.getvalue()) + + def test_stall_blocked_diagnostic_sink_is_reaped_without_touching_other_processes(self): + child = subprocess.Popen([sys.executable, '-c', + 'import os;\nwhile True: os.write(1, b"x" * 65536)'], + stdout=subprocess.PIPE, start_new_session=True) + unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) + self.addCleanup(unrelated.wait) + self.addCleanup(unrelated.kill) + self.addCleanup(child.stdout.close) + self.addCleanup(child.wait) + self.addCleanup(lambda: child.kill() if child.poll() is None else None) + observer = CAPTURE.StallObserver(self.root, self.output) + observer.child, observer.started, observer.attempted = child, time.monotonic(), True + read_fd, write_fd = os.pipe() + os.write(write_fd, b'build output') + os.close(write_fd) + with os.fdopen(read_fd, 'rb') as source: + self.assertEqual([b'build output'], list(CAPTURE.capture_chunks(source, observer))) + self.assertIsNotNone(child.poll()) + self.assertIsNone(unrelated.poll()) + + def test_stall_exited_or_reused_daemon_is_not_labelled_verified(self): + with patch.object(CAPTURE, 'stall_processes', return_value=[]), patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()) as output: + CAPTURE.collect_stall(self.root, self.output, self.stall_identity()) + self.assertIn('"daemon_attribution": "unavailable"', output.getvalue()) + for path in self.output.glob('observation-*/snapshot-*.json'): + self.assertEqual('unavailable', json.loads(path.read_text())['daemon_attribution']) + + def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): + read_fd, write_fd = os.pipe() + os.write(write_fd, b'original output\n') + os.close(write_fd) + observer = Mock() + destination = io.BytesIO() + with os.fdopen(read_fd, 'rb') as source: + status = CAPTURE.capture_log(source, destination, self.log, observer) + self.assertEqual(0, status) + self.assertEqual(b'original output\n', destination.getvalue()) + self.assertEqual(destination.getvalue(), self.log.read_bytes()) + observer.observe.assert_called_once_with(b'original output\n') + observer.close.assert_called_once() + def test_compile_failure_bounds_and_symlink_rejection(self): self.write('services/common-saga/build/generated/source/Bad.java', 'bad') self.write('services/common-saga/build/generated/source/Huge.java', 'x' * 100) diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 0466db2ea5..2c4f7134e6 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -10,6 +10,7 @@ import signal import subprocess import sys +import tempfile import time from collections import deque from pathlib import Path @@ -38,14 +39,263 @@ def safe_file(root, path): return False -def capture_log(source, destination, path): +# Account CI-only observation. No build process is signalled or restarted. +PROC_ROOT = Path('/proc') +STALL_IDLE_SECONDS = 300 +STALL_BATCH_SECONDS = 90 +STALL_COMMAND_SECONDS = 5 +STALL_MAX_PROCESSES = 8 +STALL_DUMP_BYTES = 128 * 1024 +DAEMON_PID = re.compile(rb'The client will now receive all logging from the daemon \(pid: ([0-9]+)\)') + + +def owns_session(pid): + try: + return os.getpgid(pid) == pid and os.getsid(pid) == pid + except ProcessLookupError: + return False + + +def stop_stall_session(signum, frame): + if owns_session(os.getpid()): + os.killpg(os.getpid(), signal.SIGKILL) + raise SystemExit(128 + signum) + + +def java_identity(pid): + """Classify without retaining argv, environment, or arbitrary process names.""" + try: + path = PROC_ROOT / str(pid) + if path.stat().st_uid != os.getuid(): + return None + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + with (path / 'cmdline').open('rb') as stream: + arguments = stream.read(8193) + if len(arguments) > 8192: + return None + arguments = arguments.split(b'\0') + if b'org.gradle.launcher.daemon.bootstrap.GradleDaemon' in arguments: + role = 'daemon' + elif (b'worker.org.gradle.process.internal.worker.GradleWorkerMain' in arguments + and any(arg.startswith(b'Gradle Test Executor ') for arg in arguments)): + role = 'test-worker' + else: + return None + executable = (path / 'exe').resolve(strict=True) + if executable.name != 'java': + return None + return {'pid': pid, 'ppid': int(fields[1]), 'start': int(fields[19]), + 'state': fields[0].decode('ascii'), 'role': role, + 'cpu_ticks': int(fields[11]) + int(fields[12]), 'rss_pages': int(fields[21]), + 'jcmd': str(executable.with_name('jcmd'))} + except (OSError, ValueError, IndexError, UnicodeError): + return None + + +def stall_processes(daemon): + current = java_identity(daemon['pid']) + if not current or (current['start'], current['role']) != (daemon['start'], 'daemon'): + return [] + result = [current] + # Workers are direct daemon children. Do not inspect unrelated JVMs or their arguments. + with os.scandir(PROC_ROOT) as entries: + paths = [Path(entry.path) for _, entry in zip(range(MAX_VISITED_ENTRIES), entries) + if entry.name.isdigit()] + for path in paths: + if not path.name.isdigit(): + continue + try: + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + if int(fields[1]) != daemon['pid']: + continue + except (OSError, ValueError, IndexError): + continue + worker = java_identity(int(path.name)) + if worker and worker['role'] == 'test-worker': + result.append(worker) + if len(result) >= STALL_MAX_PROCESSES: + break + return result + + +def sanitized_threads(raw): + """Allow only stack/state/monitor syntax; thread names and diagnostic prose are private.""" + lines = [] + for line in raw.decode('utf-8', errors='replace').splitlines(): + if line.startswith('"'): + identifiers = re.findall(r'(?:#\d+|(?:tid|nid)=0x[0-9a-f]+)(?=\s|$)', line[line.rfind(chr(34)) + 1:]) + lines.append('thread (name omitted) ' + ' '.join(identifiers)) + elif re.fullmatch(r'\s*java.lang.Thread.State: [A-Z_]+(?: \([a-z ]+\))?', line): + lines.append(line.strip()) + elif re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$: /\-]+\)', line): + lines.append(line.strip()) + elif re.fullmatch(r'\s*- (?:locked|waiting on|waiting to lock|parking to wait for)\s+<0x[0-9a-f]+> \(a [A-Za-z0-9_.$]+\)', line): + lines.append(line.strip()) + return '\n'.join(lines) + + +def thread_snapshot(identity): + facts = {key: value for key, value in identity.items() if key != 'jcmd'} + current = java_identity(identity['pid']) + # Counters may change; only identity and lineage must remain fixed. + keys = ('pid', 'ppid', 'start', 'role', 'jcmd') + if not current or any(current[key] != identity[key] for key in keys): + return {**facts, 'status': 'exited-or-changed'} + process = None + selector = selectors.DefaultSelector() + raw = bytearray() + status = 'complete' + try: + process = subprocess.Popen([identity['jcmd'], str(identity['pid']), 'Thread.print', '-l'], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + selector.register(process.stdout, selectors.EVENT_READ) + deadline = time.monotonic() + STALL_COMMAND_SECONDS + while True: + remaining = deadline - time.monotonic() + if remaining <= 0 or not selector.select(remaining): + status = 'timeout' + break + chunk = os.read(process.stdout.fileno(), min(8192, STALL_DUMP_BYTES - len(raw))) + if not chunk: + break + raw.extend(chunk) + if len(raw) >= STALL_DUMP_BYTES: + status = 'limited' + break + if status == 'complete': + process.wait(timeout=max(0.01, deadline - time.monotonic())) + if process.returncode: + status = 'failed' + except subprocess.TimeoutExpired: + status = 'timeout' + except OSError: + status = 'unavailable' + finally: + selector.close() + if process is not None: + if process.poll() is None: + process.kill() # Only our jcmd helper, never the target JVM. + process.wait() + process.stdout.close() + current = java_identity(identity['pid']) + if not current or any(current[key] != identity[key] for key in keys): + return {**facts, 'status': 'exited-or-changed'} + return {**facts, 'status': status, 'threads': sanitized_threads(raw)} + + +def collect_stall(root, output, daemon): + root = root.resolve() + relative = output.absolute().relative_to(root) + cursor = root + for part in relative.parts: + cursor /= part + if cursor.is_symlink(): + raise ValueError('Stall evidence must not traverse symlinks') + output.mkdir(parents=True, exist_ok=True) + # Each invocation owns a fresh directory; never overwrite prior evidence. + target = Path(tempfile.mkdtemp(prefix='observation-', dir=output)) + started = time.monotonic() + for number in range(2): + if number: + time.sleep(max(0, 30 - (time.monotonic() - started))) + processes = stall_processes(daemon) if daemon else [] + report = {'snapshot': number + 1, 'reason': '300 seconds without Gradle output', + 'daemon_attribution': 'verified' if processes else 'unavailable', + 'process_limit': STALL_MAX_PROCESSES, 'process_limit_reached': len(processes) >= STALL_MAX_PROCESSES, + 'processes': [thread_snapshot(process) for process in processes]} + payload = json.dumps(report, indent=2) + '\n' + (target / f'snapshot-{number + 1}.json').write_text(payload) + # Independent child output: a blocked log sink cannot stall Gradle capture. + print('FIREMUD_STALL_SNAPSHOT ' + json.dumps( + {key: value for key, value in report.items() if key != 'processes'}), flush=True) + for process in report['processes']: + print(json.dumps({key: value for key, value in process.items() if key != 'threads'}), flush=True) + print(process.get('threads', ''), flush=True) + + +class StallObserver: + """One independent, bounded diagnostic batch; capture remains the sole build-output reader.""" + def __init__(self, root, output): + self.root, self.output = root, output + self.last_activity = time.monotonic() + self.prefix = b'' + self.daemon = None + self.child = None + self.started = None + self.attempted = False + + def observe(self, chunk): + self.last_activity = time.monotonic() + data = self.prefix + chunk + for match in DAEMON_PID.finditer(data): + candidate = java_identity(int(match[1])) + if candidate and candidate['role'] == 'daemon': + self.daemon = candidate + self.prefix = data[-256:] + + def tick(self): + now = time.monotonic() + if self.child and now - self.started >= STALL_BATCH_SECONDS: + self.close() + if self.attempted or now - self.last_activity < STALL_IDLE_SECONDS: + return + self.attempted = True + try: + self.child = subprocess.Popen( + [sys.executable, str(Path(__file__).resolve()), '--stall-daemon', + json.dumps(self.daemon), '--root', str(self.root), '--output', str(self.output)], + stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=subprocess.DEVNULL, + start_new_session=True) + self.started = now + except OSError: + pass # Diagnostics never change the original check result. + + def close(self): + if self.child: + # The session contains only this observer and its jcmd helpers. + # Always reap its group, including a helper surviving an observer error. + try: + if owns_session(self.child.pid): + os.killpg(self.child.pid, signal.SIGKILL) + self.child.wait() + else: + self.child.poll() # Reap if exited; never wait on an unowned process. + except ProcessLookupError: + self.child.wait() + self.child = None + + +def capture_chunks(source, observer): + if observer is None: + reader = getattr(source, 'read1', source.read) + while chunk := reader(64 * 1024): + yield chunk + return + selector = selectors.DefaultSelector() + selector.register(source, selectors.EVENT_READ) + try: + while True: + observer.tick() + if not selector.select(1): + continue + chunk = os.read(source.fileno(), 64 * 1024) + if not chunk: + break + observer.observe(chunk) + yield chunk + finally: + selector.close() + observer.close() + + +def capture_log(source, destination, path, observer=None): """Forward immediately; retain only a bounded tail, even if capture fails.""" tail = deque() length = 0 forwarding = True failed = False - reader = getattr(source, 'read1', source.read) - while chunk := reader(64 * 1024): + for chunk in capture_chunks(source, observer): if forwarding: try: destination.write(chunk) @@ -317,9 +567,26 @@ def main(): parser.add_argument('--log', type=Path) parser.add_argument('--output', type=Path) parser.add_argument('--check-exit', type=int) + parser.add_argument('--stall-output', type=Path) + parser.add_argument('--stall-daemon') args = parser.parse_args() + if args.stall_daemon is not None: + # Independent ceiling also applies if the capture parent is abruptly killed. + if not owns_session(os.getpid()): + return 2 # Private mode must be started by our observer, in its own session. + signal.signal(signal.SIGALRM, stop_stall_session) + signal.alarm(STALL_BATCH_SECONDS) + collect_stall(args.root, args.output, json.loads(args.stall_daemon)) + return 0 if args.capture_log is not None: - return capture_log(sys.stdin.buffer, sys.stdout.buffer, args.capture_log) + observer = StallObserver(args.root, args.stall_output) if args.stall_output else None + if observer: + def stop(signum, frame): + observer.close() + raise SystemExit(128 + signum) + for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + signal.signal(signum, stop) + return capture_log(sys.stdin.buffer, sys.stdout.buffer, args.capture_log, observer) if any(value is None for value in (args.root, args.log, args.output, args.check_exit)): parser.error('collection requires --root, --log, --output and --check-exit') if 0 < args.check_exit < 128: From 75733f222de692cf32472bf39966dae4950d8f7b Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 05:55:40 +1300 Subject: [PATCH 47/66] Combine equivalent stall stack allowlist branches --- dev-tools/validation/collect-gradle-compile-failure.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 2c4f7134e6..29e012e537 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -125,11 +125,9 @@ def sanitized_threads(raw): if line.startswith('"'): identifiers = re.findall(r'(?:#\d+|(?:tid|nid)=0x[0-9a-f]+)(?=\s|$)', line[line.rfind(chr(34)) + 1:]) lines.append('thread (name omitted) ' + ' '.join(identifiers)) - elif re.fullmatch(r'\s*java.lang.Thread.State: [A-Z_]+(?: \([a-z ]+\))?', line): - lines.append(line.strip()) - elif re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$: /\-]+\)', line): - lines.append(line.strip()) - elif re.fullmatch(r'\s*- (?:locked|waiting on|waiting to lock|parking to wait for)\s+<0x[0-9a-f]+> \(a [A-Za-z0-9_.$]+\)', line): + elif (re.fullmatch(r'\s*java.lang.Thread.State: [A-Z_]+(?: \([a-z ]+\))?', line) + or re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$: /\-]+\)', line) + or re.fullmatch(r'\s*- (?:locked|waiting on|waiting to lock|parking to wait for)\s+<0x[0-9a-f]+> \(a [A-Za-z0-9_.$]+\)', line)): lines.append(line.strip()) return '\n'.join(lines) From 54205481a840fe50ad7f15936921aaffd042153d Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 07:53:09 +1300 Subject: [PATCH 48/66] Serialize numbered Account CI checks and expose bounded stall coverage --- .github/scripts/run-gradle-module-checks.sh | 20 +- .../tests/test_gradle_compile_failure.py | 182 +++++++++++++++++- .../collect-gradle-compile-failure.py | 148 +++++++++++--- 3 files changed, 310 insertions(+), 40 deletions(-) diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index ac66965e1d..2c3ac057eb 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -51,30 +51,46 @@ if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" ) CHECK_ARGS+=("-PslowServiceCiPartitionModule=$MODULE" "-PslowServiceCiPartition=$PARTITION") fi +# Controlled Account CI reliability experiment: serialize the complete selected check. +# Existing integrationTest logic then uses one fork; preparation and other modules stay at two. +# This does not establish the cause of the observed parallel test-dispatch shutdown wait. +CHECK_WORKERS=2 +if [[ "$MODULE" == "account-service" && "$PARTITION" != "full" ]]; then + CHECK_WORKERS=1 +fi +readonly CHECK_WORKERS + # Keep the original recovery policy and complete check; diagnostics never retry it. CHECK_LOG="$(mktemp "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/firemud-module-check.XXXXXX")" || CHECK_LOG="" readonly CHECK_LOG trap 'rm -f -- "$CHECK_LOG"' EXIT if [[ -z "$CHECK_LOG" ]]; then + printf 'FIREMUD_STALL_ACTIVATION status=disabled-capture-unavailable\n' >&2 echo "Compile-failure log unavailable; running the original check without capture" >&2 exec bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ - --max-workers=2 \ + --max-workers="$CHECK_WORKERS" \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile fi declare -a CAPTURE_ARGS=() +stall_activation=disabled-scope # Observe Account's stalled forks only on an isolated hosted Linux runner. if [[ "$MODULE" == "account-service" && "$PARTITION" != "full" && "${GITHUB_ACTIONS:-}" == true && "${RUNNER_ENVIRONMENT:-}" == github-hosted && "${RUNNER_OS:-}" == Linux ]]; then CAPTURE_ARGS+=(--root "$ROOT_DIR" --stall-output "$ROOT_DIR/build/reports/gradle-stall/$MODULE/partition-$PARTITION") + stall_activation=enabled +elif [[ "$MODULE" == "account-service" && "$PARTITION" != "full" ]]; then + stall_activation=disabled-runner-guard fi +# Fixed reason only: do not print environment values or invocation arguments. +printf 'FIREMUD_STALL_ACTIVATION status=%s\n' "$stall_activation" >&2 set +e bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ - --max-workers=2 \ + --max-workers="$CHECK_WORKERS" \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" \ "${CHECK_ARGS[@]}" \ diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 523f00aec2..ee6d37a1ac 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -51,7 +51,7 @@ def test_stall_timer_activity_attribution_and_one_batch(self): with patch.object(CAPTURE.time, 'monotonic', return_value=0) as clock, patch.object( CAPTURE, 'java_identity', return_value=identity), patch.object( CAPTURE.subprocess, 'Popen') as launch, patch.object(CAPTURE.os, 'killpg') as kill, patch.object( - CAPTURE, 'owns_session', return_value=True): + CAPTURE, 'owns_session', return_value=True), patch.object(CAPTURE.os, 'waitid', return_value=None): observer = CAPTURE.StallObserver(self.root, self.output) observer.observe(b'The client will now receive all logging from the daemon (pi') observer.observe(b'd: 123). The daemon log file: secret') @@ -94,14 +94,14 @@ def test_stall_without_daemon_and_launch_failure_are_nonfatal(self): def test_stall_processes_include_both_workers_exclude_unrelated_and_reused(self): proc = self.root / 'proc' java = self.write('jdk/bin/java') - def process(pid, parent, main, display=b''): + def process(pid, parent, main, display=b'', executable=None): base = proc / str(pid) base.mkdir(parents=True) fields = ['0'] * 22 fields[0], fields[1], fields[19] = 'S', str(parent), '42' (base / 'stat').write_text(f'{pid} (java) ' + ' '.join(fields)) (base / 'cmdline').write_bytes(b'java\0' + main + b'\0' + display + b'\0SECRET\0') - (base / 'exe').symlink_to(java) + (base / 'exe').symlink_to(executable or java) process(100, 1, b'org.gradle.launcher.daemon.bootstrap.GradleDaemon') for pid in (101, 102): process(pid, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', @@ -109,14 +109,71 @@ def process(pid, parent, main, display=b''): process(103, 999, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', b'Gradle Test Executor 5') process(104, 100, b'other.JavaMain') + process(105, 100, b'SECRET' * 2000) + process(106, 101, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b'Gradle Test Executor 6') + process(107, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b'Gradle Test Executor 7', self.write('jdk/bin/not-java')) with patch.object(CAPTURE, 'PROC_ROOT', proc): daemon = CAPTURE.java_identity(100) - selected = CAPTURE.stall_processes(daemon) + coverage = {} + selected = CAPTURE.stall_processes(daemon, coverage) + self.assertEqual(2, coverage['workers_selected']) + self.assertEqual({'selected-test-worker': 2, 'unrecognized-java-role': 1, + 'command-line-limit': 1, 'not-java-executable': 1}, coverage['selection_counts']) + self.assertEqual({101, 102, 104, 105, 107}, {c['pid'] for c in coverage['candidates']}) + self.assertNotIn('SECRET', json.dumps(coverage)) self.assertEqual({100, 101, 102}, {p['pid'] for p in selected}) self.assertNotIn('SECRET', json.dumps(selected)) self.assertEqual([], CAPTURE.stall_processes({**daemon, 'start': 43})) - with patch.object(CAPTURE, 'STALL_MAX_PROCESSES', 2): - self.assertEqual(2, len(CAPTURE.stall_processes(daemon))) + with patch.object(CAPTURE, 'STALL_MAX_PROCESSES', 2), patch.object( + CAPTURE, 'STALL_MAX_CANDIDATES', 1): + limited = {} + self.assertEqual(2, len(CAPTURE.stall_processes(daemon, limited))) + self.assertEqual(1, limited['selection_counts']['attachment-limit']) + self.assertEqual(1, len(limited['candidates'])) + self.assertEqual(4, limited['candidates_omitted']) + with patch.object(CAPTURE, 'MAX_VISITED_ENTRIES', 1): + limited = {} + CAPTURE.stall_processes(daemon, limited) + self.assertTrue(limited['scan_limit_reached']) + reason = {} + with patch.object(Path, 'open', side_effect=PermissionError('SECRET')): + self.assertIsNone(CAPTURE.java_identity(101, reason)) + self.assertEqual({'reason': 'access-denied'}, reason) + + def test_stall_coverage_distinguishes_no_children_from_no_attribution(self): + daemon = self.stall_identity() + coverage = {} + with patch.object(CAPTURE, 'java_identity', return_value=daemon), patch.object( + CAPTURE.os, 'scandir') as entries: + entries.return_value.__enter__.return_value = iter([]) + self.assertEqual([daemon], CAPTURE.stall_processes(daemon, coverage)) + self.assertEqual('verified', coverage['daemon_identity']) + self.assertEqual(0, coverage['workers_selected']) + self.assertEqual([], coverage['candidates']) + self.assertFalse(coverage['scan_limit_reached']) + with patch.object(CAPTURE, 'java_identity', return_value=None): + self.assertEqual([], CAPTURE.stall_processes(daemon, coverage)) + self.assertEqual('exited-or-changed', coverage['daemon_identity']) + + def test_stall_daemon_retains_late_frames_with_fixed_larger_ceiling(self): + fake = self.write('jcmd', '#!/usr/bin/env python3\n' + 'print("ignored" * 24000)\n' + 'print("at org.example.Late.run(Late.java:42)")\n') + fake.chmod(0o755) + for role in ('daemon', 'test-worker'): + identity = {**self.stall_identity(role=role), 'jcmd': str(fake)} + with patch.object(CAPTURE, 'java_identity', return_value=identity): + result = CAPTURE.thread_snapshot(identity) + if role == 'daemon': + self.assertEqual('complete', result['status']) + self.assertIn('Late.run', result['threads']) + self.assertEqual(512 * 1024, result['dump_byte_limit']) + else: + self.assertEqual('limited', result['status']) + self.assertNotIn('Late.run', result['threads']) + self.assertEqual(128 * 1024, result['dump_byte_limit']) def test_stall_sanitizer_rejects_names_secrets_and_diagnostic_prose(self): raw = (b'"SECRET-password" #17 tid=0xabc nid=0xdef waiting\n' @@ -240,6 +297,69 @@ def test_stall_exited_or_reused_daemon_is_not_labelled_verified(self): for path in self.output.glob('observation-*/snapshot-*.json'): self.assertEqual('unavailable', json.loads(path.read_text())['daemon_attribution']) + def test_stall_symlinked_checkout_preserves_output_containment(self): + alias = self.root / 'checkout' + actual = self.root / 'actual' + actual.mkdir() + alias.symlink_to(actual, target_is_directory=True) + with patch.object(CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()): + CAPTURE.collect_stall(alias, alias / 'build/evidence', None) + self.assertEqual(2, len(list(actual.glob('build/evidence/observation-*/snapshot-*.json')))) + (actual / 'escape').symlink_to(self.root, target_is_directory=True) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(alias, alias / 'escape/evidence', None) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(alias, alias / '../outside', None) + + def test_stall_marker_is_fixed_nonblocking_and_does_not_expose_failure_text(self): + with patch.object(CAPTURE.os, 'open', return_value=99) as opening, patch.object( + CAPTURE.os, 'write', side_effect=BlockingIOError('SECRET')) as writing, patch.object( + CAPTURE.os, 'close') as closing: + CAPTURE.stall_marker('launch-failed') + self.assertTrue(opening.call_args.args[1] & os.O_NONBLOCK) + self.assertTrue(opening.call_args.args[1] & os.O_APPEND) + self.assertEqual(b'FIREMUD_STALL_OBSERVER status=launch-failed\n', writing.call_args.args[1]) + closing.assert_called_once_with(99) + with patch.object(CAPTURE.os, 'open') as opening: + CAPTURE.stall_marker('SECRET exception path') + opening.assert_not_called() + + def test_stall_private_mode_reports_safe_setup_failure_in_subprocess(self): + output = self.root / 'escape' + output.symlink_to(self.root, target_is_directory=True) + result = subprocess.run( + [sys.executable, str(ROOT / 'dev-tools/validation/collect-gradle-compile-failure.py'), + '--stall-daemon', 'null', '--root', str(self.root), '--output', str(output)], + start_new_session=True, capture_output=True, text=True, timeout=5, check=False) + self.assertEqual(1, result.returncode) + self.assertIn('status=started', result.stdout) + self.assertIn('status=setup-failed', result.stdout) + self.assertNotIn(str(self.root), result.stdout + result.stderr) + self.assertNotIn('Traceback', result.stdout + result.stderr) + + def test_stall_enabled_capture_subprocess_preserves_bytes_through_idle_observation(self): + # Copy only the executable under test; shorten constants without attaching to a JVM. + script = self.root / 'collector.py' + script.write_text((ROOT / 'dev-tools/validation/collect-gradle-compile-failure.py').read_text() + .replace('STALL_IDLE_SECONDS = 300', 'STALL_IDLE_SECONDS = 0.01') + .replace('STALL_BATCH_SECONDS = 90', 'STALL_BATCH_SECONDS = 2')) + process = subprocess.Popen( + [sys.executable, str(script), '--capture-log', str(self.log), '--root', str(self.root), + '--stall-output', str(self.output)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + self.addCleanup(lambda: process.kill() if process.poll() is None else None) + deadline = time.monotonic() + 4 + while not list(self.output.glob('observation-*/snapshot-1.json')): + if time.monotonic() > deadline: + self.fail('bounded fake observer did not create its first snapshot') + time.sleep(0.01) + output, error = process.communicate(b'original bytes\n', timeout=5) + self.assertEqual(0, process.returncode) + self.assertEqual(b'original bytes\n', output) + self.assertIn(b'status=enabled', error) + self.assertIn(b'status=started', error) + self.assertNotIn(b'Traceback', error) + def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): read_fd, write_fd = os.pipe() os.write(write_fd, b'original output\n') @@ -254,6 +374,56 @@ def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): observer.observe.assert_called_once_with(b'original output\n') observer.close.assert_called_once() + def test_module_wrapper_serializes_only_numbered_account_checks_including_fallback(self): + for module, partition, expected in [('account-service', '4', [2, 1]), + ('account-service', 'full', [2]), + ('game-session-service', '4', [2, 2]), + ('world-management-service', 'full', [2])]: + for fallback in (False, True): + with self.subTest(module=module, partition=partition, fallback=fallback): + root = self.root / f'{module}-{partition}-{fallback}' + script = root / '.github/scripts/run-gradle-module-checks.sh' + script.parent.mkdir(parents=True) + shutil.copyfile(ROOT / '.github/scripts/run-gradle-module-checks.sh', script) + validation = root / 'dev-tools/validation' + validation.mkdir(parents=True) + shutil.copyfile(ROOT / 'dev-tools/validation/collect-gradle-compile-failure.py', + validation / 'collect-gradle-compile-failure.py') + (validation / 'run-gradle-with-dependency-recovery.sh').write_text( + '#!/bin/bash\nrunner="$2"; shift 3; exec "$runner" "$@"\n') + (validation / 'slow_service_ci_test_partition.py').write_text('# Inert planner fixture.\n') + runner = root / 'gradlew' + runner.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> calls\n' + 'printf "original-check-output\\n"\n') + runner.chmod(0o755) + env = {**os.environ, 'GITHUB_ACTIONS': 'true', 'RUNNER_ENVIRONMENT': 'github-hosted', + 'RUNNER_OS': 'Linux'} + if fallback: + binary = root / 'bin' + binary.mkdir() + mktemp = binary / 'mktemp' + mktemp.write_text('#!/bin/bash\nexit 1\n') + mktemp.chmod(0o755) + env['PATH'] = str(binary) + os.pathsep + env['PATH'] + result = subprocess.run(['bash', str(script), module, partition], cwd=root, env=env, + capture_output=True, text=True, timeout=5, check=False) + self.assertEqual(0, result.returncode, result.stderr) + calls = (root / 'calls').read_text().splitlines() + self.assertEqual(len(expected), len(calls)) + for call, workers in zip(calls, expected, strict=True): + self.assertIn(f'--max-workers={workers}', call) + self.assertIn('-PfullCheck', call) + self.assertNotIn('--tests', call) + self.assertEqual(len(expected), result.stdout.count('original-check-output')) + if partition != 'full': + self.assertIn(f'-PslowServiceCiPartition={partition}', calls[-1]) + self.assertIn(f':{module}:testClasses', calls[0]) + self.assertIn(f':{module}:check', calls[-1]) + marker = ('disabled-capture-unavailable' if fallback else + 'enabled' if module == 'account-service' and partition != 'full' else + 'disabled-scope') + self.assertIn(f'FIREMUD_STALL_ACTIVATION status={marker}', result.stderr) + def test_compile_failure_bounds_and_symlink_rejection(self): self.write('services/common-saga/build/generated/source/Bad.java', 'bad') self.write('services/common-saga/build/generated/source/Huge.java', 'x' * 100) diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 29e012e537..e5c6189fb1 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -45,10 +45,29 @@ def safe_file(root, path): STALL_BATCH_SECONDS = 90 STALL_COMMAND_SECONDS = 5 STALL_MAX_PROCESSES = 8 +STALL_MAX_CANDIDATES = 32 STALL_DUMP_BYTES = 128 * 1024 DAEMON_PID = re.compile(rb'The client will now receive all logging from the daemon \(pid: ([0-9]+)\)') +def stall_marker(status, fd=2): + """Fixed, best-effort status only; never block capture or change shared descriptor flags.""" + if status not in {'enabled', 'started', 'completed', 'launch-failed', 'setup-failed', + 'observer-failed', 'session-unowned', 'deadline', 'cancelled'}: + return + descriptor = None + try: + # Reopening proc fd creates a separate description; dup()+F_SETFL would also + # make the caller's pipe nonblocking. O_APPEND protects regular-file sinks. + descriptor = os.open(f'/proc/self/fd/{fd}', os.O_WRONLY | os.O_NONBLOCK | os.O_APPEND) + os.write(descriptor, f'FIREMUD_STALL_OBSERVER status={status}\n'.encode('ascii')) + except OSError: + pass + finally: + if descriptor is not None: + os.close(descriptor) + + def owns_session(pid): try: return os.getpgid(pid) == pid and os.getsid(pid) == pid @@ -57,22 +76,27 @@ def owns_session(pid): def stop_stall_session(signum, frame): + stall_marker('deadline', fd=1) if owns_session(os.getpid()): os.killpg(os.getpid(), signal.SIGKILL) raise SystemExit(128 + signum) -def java_identity(pid): +def java_identity(pid, rejection=None): """Classify without retaining argv, environment, or arbitrary process names.""" + def reject(reason): + if rejection is not None: + rejection['reason'] = reason + try: path = PROC_ROOT / str(pid) if path.stat().st_uid != os.getuid(): - return None + return reject('different-uid') fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() with (path / 'cmdline').open('rb') as stream: arguments = stream.read(8193) if len(arguments) > 8192: - return None + return reject('command-line-limit') arguments = arguments.split(b'\0') if b'org.gradle.launcher.daemon.bootstrap.GradleDaemon' in arguments: role = 'daemon' @@ -80,41 +104,72 @@ def java_identity(pid): and any(arg.startswith(b'Gradle Test Executor ') for arg in arguments)): role = 'test-worker' else: - return None + return reject('unrecognized-java-role') executable = (path / 'exe').resolve(strict=True) if executable.name != 'java': - return None + return reject('not-java-executable') return {'pid': pid, 'ppid': int(fields[1]), 'start': int(fields[19]), 'state': fields[0].decode('ascii'), 'role': role, 'cpu_ticks': int(fields[11]) + int(fields[12]), 'rss_pages': int(fields[21]), 'jcmd': str(executable.with_name('jcmd'))} + except (FileNotFoundError, ProcessLookupError): + return reject('exited') + except PermissionError: + return reject('access-denied') except (OSError, ValueError, IndexError, UnicodeError): - return None + return reject('process-unavailable') -def stall_processes(daemon): +def stall_processes(daemon, coverage=None): + if coverage is None: + coverage = {} + coverage.update({'scope': 'same-uid-direct-daemon-children', 'scan_limit': MAX_VISITED_ENTRIES, + 'scan_limit_reached': False, 'entries_examined': 0, 'inspection_errors': 0, + 'candidate_limit': STALL_MAX_CANDIDATES, 'candidates': [], + 'candidates_omitted': 0, 'selection_counts': {}, 'workers_selected': 0}) current = java_identity(daemon['pid']) if not current or (current['start'], current['role']) != (daemon['start'], 'daemon'): + coverage['daemon_identity'] = 'exited-or-changed' return [] + coverage['daemon_identity'] = 'verified' result = [current] - # Workers are direct daemon children. Do not inspect unrelated JVMs or their arguments. + # Scope intentionally remains direct children. Rejected candidates are metadata, + # not permission to attach to an unknown JVM or scan its descendants/arguments. with os.scandir(PROC_ROOT) as entries: - paths = [Path(entry.path) for _, entry in zip(range(MAX_VISITED_ENTRIES), entries) - if entry.name.isdigit()] - for path in paths: - if not path.name.isdigit(): - continue - try: - fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() - if int(fields[1]) != daemon['pid']: + for _, entry in zip(range(MAX_VISITED_ENTRIES), entries): + coverage['entries_examined'] += 1 + if not entry.name.isdigit(): continue - except (OSError, ValueError, IndexError): - continue - worker = java_identity(int(path.name)) - if worker and worker['role'] == 'test-worker': - result.append(worker) - if len(result) >= STALL_MAX_PROCESSES: - break + path = Path(entry.path) + try: + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + if int(fields[1]) != daemon['pid'] or path.stat().st_uid != os.getuid(): + continue + candidate = {'pid': int(entry.name), 'ppid': int(fields[1]), + 'start': int(fields[19]), 'state': fields[0].decode('ascii')} + except (OSError, ValueError, IndexError, UnicodeError): + coverage['inspection_errors'] += 1 + continue + rejection = {} + worker = java_identity(candidate['pid'], rejection) + reason = rejection.get('reason', 'unrecognized-java-role') + if worker and worker['role'] == 'test-worker': + if any(worker[key] != candidate[key] for key in ('pid', 'ppid', 'start')): + reason = 'identity-changed' + elif len(result) >= STALL_MAX_PROCESSES: + reason = 'attachment-limit' + else: + result.append(worker) + coverage['workers_selected'] += 1 + reason = 'selected-test-worker' + candidate['selection'] = reason + counts = coverage['selection_counts'] + counts[reason] = counts.get(reason, 0) + 1 + if len(coverage['candidates']) < STALL_MAX_CANDIDATES: + coverage['candidates'].append(candidate) + else: + coverage['candidates_omitted'] += 1 + coverage['scan_limit_reached'] = coverage['entries_examined'] >= MAX_VISITED_ENTRIES return result @@ -134,6 +189,9 @@ def sanitized_threads(raw): def thread_snapshot(identity): facts = {key: value for key, value in identity.items() if key != 'jcmd'} + # The observed daemon exceeded128KiB; retain later actor frames with a fixed ceiling. + dump_limit = STALL_DUMP_BYTES * (4 if identity['role'] == 'daemon' else 1) + facts['dump_byte_limit'] = dump_limit current = java_identity(identity['pid']) # Counters may change; only identity and lineage must remain fixed. keys = ('pid', 'ppid', 'start', 'role', 'jcmd') @@ -154,11 +212,11 @@ def thread_snapshot(identity): if remaining <= 0 or not selector.select(remaining): status = 'timeout' break - chunk = os.read(process.stdout.fileno(), min(8192, STALL_DUMP_BYTES - len(raw))) + chunk = os.read(process.stdout.fileno(), min(8192, dump_limit - len(raw))) if not chunk: break raw.extend(chunk) - if len(raw) >= STALL_DUMP_BYTES: + if len(raw) >= dump_limit: status = 'limited' break if status == 'complete': @@ -183,8 +241,10 @@ def thread_snapshot(identity): def collect_stall(root, output, daemon): - root = root.resolve() - relative = output.absolute().relative_to(root) + lexical_root = Path(os.path.abspath(root)) + relative = Path(os.path.abspath(output)).relative_to(lexical_root) + root = lexical_root.resolve() + output = root / relative cursor = root for part in relative.parts: cursor /= part @@ -197,9 +257,11 @@ def collect_stall(root, output, daemon): for number in range(2): if number: time.sleep(max(0, 30 - (time.monotonic() - started))) - processes = stall_processes(daemon) if daemon else [] + coverage = {'daemon_identity': 'unavailable'} + processes = stall_processes(daemon, coverage) if daemon else [] report = {'snapshot': number + 1, 'reason': '300 seconds without Gradle output', 'daemon_attribution': 'verified' if processes else 'unavailable', + 'worker_coverage': coverage, 'process_limit': STALL_MAX_PROCESSES, 'process_limit_reached': len(processes) >= STALL_MAX_PROCESSES, 'processes': [thread_snapshot(process) for process in processes]} payload = json.dumps(report, indent=2) + '\n' @@ -234,8 +296,21 @@ def observe(self, chunk): def tick(self): now = time.monotonic() - if self.child and now - self.started >= STALL_BATCH_SECONDS: - self.close() + if self.child: + # Observe without reaping: the reserved PID still owns the cleanup group. + try: + exited = os.waitid(os.P_PID, self.child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + except OSError: + stall_marker('observer-failed') + self.close() + return + if exited is not None: + if exited.si_status: + stall_marker('observer-failed') + self.close() + elif now - self.started >= STALL_BATCH_SECONDS: + stall_marker('deadline') + self.close() if self.attempted or now - self.last_activity < STALL_IDLE_SECONDS: return self.attempted = True @@ -247,7 +322,7 @@ def tick(self): start_new_session=True) self.started = now except OSError: - pass # Diagnostics never change the original check result. + stall_marker('launch-failed') # Never include exception text or paths. def close(self): if self.child: @@ -571,15 +646,24 @@ def main(): if args.stall_daemon is not None: # Independent ceiling also applies if the capture parent is abruptly killed. if not owns_session(os.getpid()): + stall_marker('session-unowned', fd=1) return 2 # Private mode must be started by our observer, in its own session. signal.signal(signal.SIGALRM, stop_stall_session) signal.alarm(STALL_BATCH_SECONDS) - collect_stall(args.root, args.output, json.loads(args.stall_daemon)) + stall_marker('started', fd=1) + try: + collect_stall(args.root, args.output, json.loads(args.stall_daemon)) + except (OSError, ValueError): + stall_marker('setup-failed', fd=1) + return 1 + stall_marker('completed', fd=1) return 0 if args.capture_log is not None: observer = StallObserver(args.root, args.stall_output) if args.stall_output else None if observer: + stall_marker('enabled') def stop(signum, frame): + stall_marker('cancelled') observer.close() raise SystemExit(128 + signum) for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): From 2c5bfc6129723cff130081a66a25986cf18555bc Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 09:25:20 +1300 Subject: [PATCH 49/66] fix(ci): qualify exact typed refresh transition diagnostics --- .github/workflows/runtime-images.yml | 17 ++++- .github/workflows/smoke.yml | 42 ++++++++--- .../architecture/system-architecture-cicd.md | 2 +- .../player-access-and-session.md | 2 +- .../pr-required-gate-context-contract.sh | 75 ++++++++++++++++--- .../pr-runtime-image-publication-contract.sh | 17 ++++- 6 files changed, 127 insertions(+), 28 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 43de0a6d0a..c0726402e0 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -74,6 +74,7 @@ jobs: image_tag: ${{ steps.meta.outputs.image_tag }} candidate_tag: ${{ steps.meta.outputs.candidate_tag }} base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} permissions: @@ -117,6 +118,7 @@ jobs: BASE_REF="" BASE_SHA="" MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false if [ "$EVENT_NAME" = "pull_request" ]; then PR_NUMBER="$EVENT_PR_NUMBER" BASE_REF="$EVENT_BASE_REF" @@ -218,6 +220,12 @@ jobs: echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 exit 1 } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi elif [ "${{ github.event_name }}" = "workflow_run" ]; then [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { echo "Runtime branch publication requires a CI push workflow run." >&2 @@ -270,6 +278,7 @@ jobs: echo "image_tag=${IMAGE_TAG}" echo "candidate_tag=${CANDIDATE_TAG}" echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" } >> "$GITHUB_OUTPUT" - name: Verify successful CI push for manual publication @@ -1785,9 +1794,13 @@ jobs: # original failed step and the final required-smoke failure remain red. - name: Known canonical transition PLAY failure with successful authenticated cleanup if: >- - ${{ always() && github.event_name == 'pull_request' && + ${{ always() && github.repository == 'benhook1013/FireMUD' && - contains(github.event.pull_request.labels.*.name, 'canonical-play-transition') && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.runtime-smoke.outcome == 'failure' && steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 7906fde96c..e3a78ec365 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "e337cb510a2ac861f823e62ad4e31026ab1c0734f4103f21b4d98a14c30eefb4"; + const canonicalRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", "dev-tools/smoke/smoke_common.py": "a1e36948b500ac796295560cb8c22321ebe47eab78be9e1f4d58837053547534", @@ -783,7 +783,7 @@ jobs: // Canonical-transition diagnostic acceptance never becomes passing producer proof. async function verifyKnownPlayFailure(run, candidate, identity) { if (repositoryName !== "benhook1013/FireMUD" || - run.event !== "pull_request") return false; + !["pull_request", "repository_dispatch"].includes(run.event)) return false; if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; const { data: source } = await withTransientGitHubRetry( "exact runtime workflow attempt lookup", @@ -798,13 +798,17 @@ jobs: source.status !== "completed" || source.conclusion !== "failure" || source.path !== workflowPath || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || - source.event !== "pull_request" + source.event !== run.event ) return false; const expectedHeadRepository = context.payload.pull_request.head.repo?.full_name; if (typeof expectedHeadRepository !== "string" || expectedHeadRepository !== repositoryName || source.head_repository?.full_name !== expectedHeadRepository) return false; - if (source.head_sha !== identity.headSha) return false; + if (source.event === "pull_request" && source.head_sha !== identity.headSha) return false; + if (source.event === "repository_dispatch" && ( + source.head_branch !== context.payload.repository.default_branch || + !/^[0-9a-f]{40}$/.test(source.head_sha ?? "") + )) return false; const { data: workflow } = await withTransientGitHubRetry( "runtime workflow identity lookup", () => github.rest.actions.getWorkflow({ owner, repo, workflow_id: source.workflow_id }) @@ -845,14 +849,18 @@ jobs: (step.conclusion === "failure" && !expectedFailures.includes(step.name))) || jobs.some((other) => other.id !== job.id && (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; - // The workflow and classifier bytes must all belong to the verified PR test merge. + // Typed refresh workflow authority is its native default-branch revision; + // the executed classifier source still belongs to the verified PR merge. + const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; for (const [path, expectedSha256] of Object.entries({ [workflowPath]: canonicalRuntimeWorkflowSha256, ...canonicalPlayClassifierSha256, })) { const { data: definition } = await withTransientGitHubRetry( `immutable PLAY classifier definition lookup: ${path}`, - () => github.rest.repos.getContent({ owner, repo, path, ref: identity.mergeSha }) + () => github.rest.repos.getContent({ + owner, repo, path, ref: path === workflowPath ? workflowSha : identity.mergeSha, + }) ); if (definition.type !== "file" || definition.path !== path || definition.encoding !== "base64" || typeof definition.content !== "string") return false; @@ -867,17 +875,29 @@ jobs: ); if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || latest.status !== "completed" || latest.conclusion !== "failure") return false; - // The producer marker attests the source event label under the fingerprinted - // workflow. Recheck the live PR label here so removal closes the exception. + // The fingerprinted marker attests the PR event label or the typed + // refresh's verified live PR label. Removal closes either exception. const { data: currentPullRequest } = await withTransientGitHubRetry( "current canonical transition label lookup", () => github.rest.pulls.get({ owner, repo, pull_number: Number(prNumber) }) ); - return currentPullRequest.state === "open" && + if (!(currentPullRequest.state === "open" && + currentPullRequest.head?.repo?.full_name === repositoryName && + currentPullRequest.base?.repo?.full_name === repositoryName && currentPullRequest.head?.sha === identity.headSha && currentPullRequest.base?.ref === identity.baseRef && Array.isArray(currentPullRequest.labels) && - currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"); + currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"))) return false; + if (source.event === "repository_dispatch") { + if (currentPullRequest.merge_commit_sha !== identity.mergeSha) return false; + const { data: currentBase } = await withTransientGitHubRetry( + "current canonical transition base ref lookup", + () => github.rest.git.getRef({ owner, repo, ref: `heads/${identity.baseRef}` }) + ); + if (currentBase.ref !== `refs/heads/${identity.baseRef}` || + currentBase.object?.sha !== identity.baseSha) return false; + } + return true; } // Commit objects are immutable; mutable PR/base reads stay fresh. @@ -1182,7 +1202,7 @@ jobs: return; } if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && - matching.event === "pull_request") { + ["pull_request", "repository_dispatch"].includes(matching.event)) { let knownPlayVerified = false; try { const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 887ca6c3e4..a489a62e9e 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,7 +88,7 @@ A typed runtime refresh hands off publication explicitly after its required cred The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose source `pull_request` event and current live PR both carry the `canonical-play-transition` label, only for the exact verified PR-event base/head/merge tuple and latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers are always fingerprinted at the tested PR merge. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. The step-independent producer guarantee is bound to one SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. This single fingerprint is part of the owning workflows, not a separate proof registry. 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 938b854ad5..4842208e7a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ Account initial/current/final creation owners, explicit initial billing-owner co ### Temporary canonical PLAY transition exception -The existing canonical-cutover stack may opt into the [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) with the `canonical-play-transition` label. The source event and live PR must both have it. This includes #3390 and, only if deliberately labeled, dependent #3405, #3409, #3407, #3408 and #3410; #3403 is not approved for the exception and must remain unlabeled. This PR list records the approved operational scope, not a workflow PR-number allowlist: applying the label is the workflow scope control, and maintainers must limit it to these approved cuts. The workflow independently checks repository, event, exact PR tuple, classified failure, qualification and cleanup. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. +The existing canonical-cutover stack may opt into the [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) with the `canonical-play-transition` label. The live PR must carry it; PR-event producers also require the event label, while typed base-refresh producers use the verified live PR label and exact current tuple. Typed-refresh support requires the updated producer workflow on the default branch and fresh evidence; it cannot qualify an earlier failed run without the marker. This includes #3390 and, only if deliberately labeled, dependent #3405, #3409, #3407, #3408 and #3410; #3403 is not approved for the exception and must remain unlabeled. This PR list records the approved operational scope, not a workflow PR-number allowlist: applying the label is the workflow scope control, and maintainers must limit it to these approved cuts. The workflow independently checks repository, event, exact PR tuple, classified failure, qualification and cleanup. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. ### Direct-text scope and JOIN identifier cutover diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 3155b7b26f..2ec7a6300a 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -548,6 +548,8 @@ for path in classifier_paths: } Path(sys.argv[2] + ".classifiers.json").write_text(json.dumps(classifier_definitions)) producer_job = producer["jobs"]["pr-local-smoke"] +if producer["jobs"]["image-meta"]["outputs"].get("canonical_play_transition") != "${{ steps.meta.outputs.canonical_play_transition }}": + raise SystemExit("Typed-refresh PLAY marker authority must come from verified image metadata") cancelled_inventory = re.search( r"const preExecutionCancelledJobNames = new Set\(\[([\s\S]*?)\]\);", script ) @@ -578,6 +580,8 @@ marker = next(step for step in steps if step.get("name") == "Known canonical tra for clause in ( "always()", "github.event_name == 'pull_request'", "github.repository == 'benhook1013/FireMUD'", "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", "needs.image-meta.outputs.runtime_smoke_required == 'true'", + "github.event_name == 'repository_dispatch'", "github.event.action == 'pr-runtime-base-refresh'", + "needs.image-meta.outputs.canonical_play_transition == 'true'", "steps.runtime-smoke.outcome == 'failure'", "steps.runtime-cleanup.outcome == 'success'", "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", ): @@ -3421,6 +3425,7 @@ const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256 const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".classifiers.json", "utf8")); const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); +const workflowSha = "d".repeat(40); const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; const run = {id: 99, run_attempt: 2, event: "pull_request"}; const failures = ["Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup"]; @@ -3433,19 +3438,31 @@ const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: steps: [...failures.map(name => step(name, "failure")), step("Stop smoke stack", "success"), step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; -async function verify(mutate = () => {}) { +async function verify(mutate = () => {}, event = "pull_request") { const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, eventHeadRepository: repositoryName, - currentPullRequest: {state: "open", head: {sha: headSha}, base: {ref: "develop"}, labels: [{name: "canonical-play-transition"}]}, + currentPullRequest: {state: "open", head: {sha: headSha, repo: {full_name: repositoryName}}, + base: {ref: "develop", repo: {full_name: repositoryName}}, merge_commit_sha: mergeSha, + labels: [{name: "canonical-play-transition"}]}, + currentBase: {ref: "refs/heads/develop", object: {sha: baseSha}}, definitions: {...classifierDefinitions, [workflowPath]: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}}); + if (event === "repository_dispatch") { + data.run.event = data.source.event = data.latest.event = event; + data.source.head_branch = data.latest.head_branch = "develop"; + data.source.head_sha = data.latest.head_sha = workflowSha; + data.candidate.head_sha = data.jobs[0].head_sha = workflowSha; + } mutate(data); const contentRequests = []; const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, rest: {actions: {getWorkflow: async () => ({data: {id: 7, path: workflowPath, name: "Build Runtime Images"}}), - getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, repos: {getContent: async ({owner, repo, path, ref}) => { + getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, + git: {getRef: async ({ref}) => {assert.equal(ref, `heads/${data.identity.baseRef}`); return {data: data.currentBase};}}, + repos: {getContent: async ({owner, repo, path, ref}) => { assert.equal(`${owner}/${repo}`, repositoryName); - assert.equal(ref, mergeSha, "PLAY classifier attestation must use the immutable verified merge"); + assert.equal(ref, path === workflowPath && event === "repository_dispatch" ? workflowSha : mergeSha, + "workflow attestation must use its executed revision; classifier attestation must use the verified merge"); contentRequests.push(path); if (!data.definitions[path]) throw Object.assign(new Error("definition unavailable"), {status: 404}); return {data: data.definitions[path]}; @@ -3455,7 +3472,8 @@ async function verify(mutate = () => {}) { `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPlayClassifierSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), - {payload: {pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); + {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, + "benhook1013", "FireMUD", require, data); if (accepted) assert.deepEqual(contentRequests, [workflowPath, ...Object.keys(classifierDefinitions)]); return accepted; } @@ -3464,7 +3482,7 @@ const failedStart = script.indexOf('if (matching.conclusion !== "success")'); const failedEnd = script.indexOf("const latestIdentity", failedStart); const failedBranch = script.slice(failedStart, failedEnd); class TerminalGitHubRequestError extends Error {} -async function failedProof(stage, error) { +async function failedProof(stage, error, event = "pull_request") { const warnings = [], failures = [], outputs = []; const github = {paginate: async () => { if (stage === "jobs") throw error; @@ -3476,7 +3494,7 @@ async function failedProof(stage, error) { "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", `return (async () => { smokeGatePolling: while (true) { ${failedBranch} break; } })();`); - await execute({...source}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, + await execute({...source, event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, TerminalGitHubRequestError, core); assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); @@ -3487,7 +3505,9 @@ async function failedProof(stage, error) { const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { "github.event_name": "pull_request", "github.repository": repositoryName, + "github.event.action": "pr-runtime-base-refresh", "github.event.pull_request.labels.*.name": ["canonical-play-transition"], + "needs.image-meta.outputs.canonical_play_transition": "false", "needs.image-meta.outputs.runtime_smoke_required": "true", "steps.runtime-smoke.outcome": "failure", "steps.runtime-smoke.outputs.known_play_failure": "direct-backend-play-entitlement-unavailable-after-login", "steps.runtime-cleanup.outcome": "success", @@ -3501,8 +3521,10 @@ function markerAccepted(overrides = {}) { return new Function("includes", `return (${expression});`)((values, value) => values.includes(value)); } (async () => { - for (const stage of ["jobs", "proof", "malformed-jobs"]) { - await failedProof(stage, Object.assign(new Error("unavailable"), {status: 404})); + for (const event of ["pull_request", "repository_dispatch"]) { + for (const stage of ["jobs", "proof", "malformed-jobs"]) { + await failedProof(stage, Object.assign(new Error("unavailable"), {status: 404}), event); + } } await failedProof("proof", null); for (const stage of ["jobs", "proof"]) { @@ -3510,6 +3532,15 @@ function markerAccepted(overrides = {}) { await assert.rejects(failedProof(stage, terminal), error => error === terminal); } assert.equal(markerAccepted(), true); + const refreshMarker = {"github.event_name": "repository_dispatch", + "github.event.pull_request.labels.*.name": [], "needs.image-meta.outputs.canonical_play_transition": "true"}; + assert.equal(markerAccepted(refreshMarker), true); + for (const overrides of [ + {"github.event.action": "other"}, {"needs.image-meta.outputs.canonical_play_transition": "false"}, + {"needs.image-meta.outputs.canonical_play_transition": ""}, {"steps.runtime-cleanup.outcome": "failure"}, + {"steps.runtime-smoke.outputs.known_play_failure": ""}, {"steps.runtime-smoke.outcome": "success"}, + {"needs.image-meta.outputs.runtime_smoke_required": "false"}, {"github.repository": "attacker/FireMUD"}, + ]) assert.equal(markerAccepted({...refreshMarker, ...overrides}), false); for (const overrides of [ {"steps.runtime-smoke.outputs.known_play_failure": ""}, {"steps.runtime-smoke.outputs.known_play_failure": "malformed"}, @@ -3523,6 +3554,7 @@ function markerAccepted(overrides = {}) { {"github.event_name": "workflow_run"}, ]) assert.equal(markerAccepted(overrides), false); assert.equal(await verify(), true); + assert.equal(await verify(() => {}, "repository_dispatch"), true); for (const path of Object.keys(classifierDefinitions)) { assert.equal(await verify(d => { const altered = Buffer.concat([Buffer.from(d.definitions[path].content, "base64"), Buffer.from("\n# altered classifier\n")]); @@ -3543,13 +3575,16 @@ function markerAccepted(overrides = {}) { d => {d.currentPullRequest.labels = [];}, d => {d.currentPullRequest.labels = [{name: "other"}];}, d => {d.currentPullRequest.state = "closed";}, - d => {d.currentPullRequest.head.sha = "d".repeat(40);}, + d => {d.currentPullRequest.head.sha = "e".repeat(40);}, + d => {d.currentPullRequest.head.repo.full_name = "attacker/FireMUD";}, + d => {d.currentPullRequest.base.repo.full_name = "attacker/FireMUD";}, d => {d.eventHeadRepository = "fork-owner/FireMUD"; d.source.head_repository.full_name = d.eventHeadRepository;}, d => {d.currentPullRequest.base.ref = "main";}, d => {d.identity.baseSha = "d".repeat(40);}, d => {d.identity.headSha = "d".repeat(40);}, d => {d.identity.mergeSha = "d".repeat(40);}, - d => {d.run.event = "repository_dispatch";}, + d => {d.run.event = "workflow_dispatch";}, + d => {d.source.event = "workflow_run";}, d => {d.source.run_attempt = 1;}, d => {d.latest.run_attempt = 3; assert.equal(d.source.run_attempt, 2);}, d => {d.latest.conclusion = "success"; assert.equal(d.source.conclusion, "failure");}, @@ -3565,7 +3600,23 @@ function markerAccepted(overrides = {}) { d => {d.jobs[0].steps.find(s => s.name.startsWith("Export fixed")).conclusion = "success";}, d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Export fixed"));}, d => {d.source.conclusion = "success";}, - ]) assert.equal(await verify(mutate), false, mutate.toString()); + d => {d.jobs = [];}, + d => {d.jobs[0].steps = [];}, + d => {delete d.jobs[0].steps;}, + ]) { + for (const event of ["pull_request", "repository_dispatch"]) { + assert.equal(await verify(mutate, event), false, `${event}: ${mutate.toString()}`); + } + } + for (const mutate of [ + d => {d.source.head_branch = "feature/untrusted";}, + d => {d.source.head_sha = "invalid";}, + d => {d.source.event = "pull_request";}, + d => {d.currentPullRequest.merge_commit_sha = "e".repeat(40);}, + d => {d.currentBase.object.sha = "e".repeat(40);}, + d => {d.currentBase.ref = "refs/heads/main";}, + d => {delete d.currentBase.object;}, + ]) assert.equal(await verify(mutate, "repository_dispatch"), false, mutate.toString()); console.log("Canonical PLAY transition exception positive and negative contracts passed."); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 2110584c9d..f045296465 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -471,6 +471,20 @@ try: assert f"base_ref={request['base']['ref']}\n" in output assert f"image_tag=pr-merge-{merge['sha']}\n" in output assert f"base_image=ghcr.io/benhook1013/firemud-base:{merge['sha']}\n" in output + assert "canonical_play_transition=false\n" in output + labeled_request = json.loads(json.dumps(request)) + labeled_request["labels"] = [{"name": "canonical-play-transition"}] + assert admit(labeled_request, merge, branch).returncode == 0 + assert "canonical_play_transition=true\n" in Path(env["GITHUB_OUTPUT"]).read_text() + # Event labels are a separate marker path; only typed-refresh admission may + # export verified live-label authority through this metadata output. + assert admit(labeled_request, merge, branch, event_name="pull_request").returncode == 0 + assert "canonical_play_transition=false\n" in Path(env["GITHUB_OUTPUT"]).read_text() + for labels in (None, [], [{"name": "other"}], "canonical-play-transition"): + unlabeled_request = {**request, "labels": labels} + assert admit(unlabeled_request, merge, branch).returncode == 0 + assert "canonical_play_transition=false\n" in Path(env["GITHUB_OUTPUT"]).read_text() + assert admit(labeled_request, merge, branch, {"EVENT_ACTION": "other"}).returncode != 0 assert branch["object"]["sha"] not in dict(line.split("=", 1) for line in output.splitlines())["base_image"] literal_marker = fixture / "must-not-execute" valid_refs = ("feature/topic+fix", "feature/@/parent", "feature/世界", "feature/#fragment", "feature/%encoded", @@ -496,7 +510,7 @@ try: assert not (fixture / "runtime-meta-ref-calls").read_text(), "invalid ref reached GitHub lookup" assert admit(request, merge, {**branch, "ref": "refs/heads/feature/other"}).returncode != 0 for mutation in ("stale-base", "stale-head", "wrong-parents", "fork", "closed", "retarget", "missing-merge", "wrong-default-ref"): - mutated_request, mutated_merge, mutated_branch = [json.loads(json.dumps(payload)) for payload in (request, merge, branch)] + mutated_request, mutated_merge, mutated_branch = [json.loads(json.dumps(payload)) for payload in (labeled_request, merge, branch)] overrides = {} if mutation == "stale-base": mutated_branch["object"]["sha"] = "d" * 40 @@ -516,6 +530,7 @@ try: overrides["GITHUB_REF"] = "refs/heads/feature/untrusted" rejected = admit(mutated_request, mutated_merge, mutated_branch, overrides) assert rejected.returncode != 0, f"runtime metadata admitted {mutation}" + assert "canonical_play_transition=true\n" not in Path(env["GITHUB_OUTPUT"]).read_text() finally: for path, original in zip(paths, originals): path.write_text(original) From 37436babe54e3b6355cc4da25a3039d6d2149fec Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 09:41:11 +1300 Subject: [PATCH 50/66] fix(ci): recognize quoted Gradle workers in bounded stall snapshots --- .github/scripts/run-gradle-module-checks.sh | 13 +---- .../tests/test_gradle_compile_failure.py | 54 ++++++++++++++++--- .../collect-gradle-compile-failure.py | 11 ++-- 3 files changed, 57 insertions(+), 21 deletions(-) diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 2c3ac057eb..4523c4344f 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -51,15 +51,6 @@ if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" ) CHECK_ARGS+=("-PslowServiceCiPartitionModule=$MODULE" "-PslowServiceCiPartition=$PARTITION") fi -# Controlled Account CI reliability experiment: serialize the complete selected check. -# Existing integrationTest logic then uses one fork; preparation and other modules stay at two. -# This does not establish the cause of the observed parallel test-dispatch shutdown wait. -CHECK_WORKERS=2 -if [[ "$MODULE" == "account-service" && "$PARTITION" != "full" ]]; then - CHECK_WORKERS=1 -fi -readonly CHECK_WORKERS - # Keep the original recovery policy and complete check; diagnostics never retry it. CHECK_LOG="$(mktemp "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/firemud-module-check.XXXXXX")" || CHECK_LOG="" readonly CHECK_LOG @@ -69,7 +60,7 @@ if [[ -z "$CHECK_LOG" ]]; then echo "Compile-failure log unavailable; running the original check without capture" >&2 exec bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ - --max-workers="$CHECK_WORKERS" \ + --max-workers=2 \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile fi @@ -90,7 +81,7 @@ printf 'FIREMUD_STALL_ACTIVATION status=%s\n' "$stall_activation" >&2 set +e bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ - --max-workers="$CHECK_WORKERS" \ + --max-workers=2 \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" \ "${CHECK_ARGS[@]}" \ diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index ee6d37a1ac..465e29fe61 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -100,20 +100,20 @@ def process(pid, parent, main, display=b'', executable=None): fields = ['0'] * 22 fields[0], fields[1], fields[19] = 'S', str(parent), '42' (base / 'stat').write_text(f'{pid} (java) ' + ' '.join(fields)) - (base / 'cmdline').write_bytes(b'java\0' + main + b'\0' + display + b'\0SECRET\0') + (base / 'cmdline').write_bytes(b'java\0-Dfixture=SECRET\0' + main + b'\0' + display + b'\0') (base / 'exe').symlink_to(executable or java) process(100, 1, b'org.gradle.launcher.daemon.bootstrap.GradleDaemon') for pid in (101, 102): process(pid, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', - b'Gradle Test Executor 4') + b"'Gradle Test Executor 4'") process(103, 999, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', - b'Gradle Test Executor 5') + b"'Gradle Test Executor 5'") process(104, 100, b'other.JavaMain') process(105, 100, b'SECRET' * 2000) process(106, 101, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', - b'Gradle Test Executor 6') + b"'Gradle Test Executor 6'") process(107, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', - b'Gradle Test Executor 7', self.write('jdk/bin/not-java')) + b"'Gradle Test Executor 7'", self.write('jdk/bin/not-java')) with patch.object(CAPTURE, 'PROC_ROOT', proc): daemon = CAPTURE.java_identity(100) coverage = {} @@ -142,6 +142,46 @@ def process(pid, parent, main, display=b'', executable=None): self.assertIsNone(CAPTURE.java_identity(101, reason)) self.assertEqual({'reason': 'access-denied'}, reason) + def test_stall_worker_launch_shape_is_exact_and_bounded(self): + proc = self.root / 'proc' + base = proc / '123' + base.mkdir(parents=True) + java = self.write('jdk/bin/java') + (base / 'exe').symlink_to(java) + fields = ['0'] * 22 + fields[0], fields[1], fields[19] = 'S', '100', '42' + (base / 'stat').write_text('123 (java) ' + ' '.join(fields)) + main = b'worker.org.gradle.process.internal.worker.GradleWorkerMain' + label = b"'Gradle Test Executor 3'" + # The classpath @file precedes the explicit main and is never opened. + valid = [b'java', b'-Xmx512m', b'@/unreadable/classpath', main, label] + cases = [ + (valid, True), + ([b'java', main, b"'Gradle Worker Daemon 3'"], False), + ([b'java', main, b'Gradle Test Executor 3'], False), + ([b'java', main, b'"Gradle Test Executor 3"'], False), + ([b'java', main, b"'Gradle Test Executor 3' suffix"], False), + ([b'java', main, b"'Gradle Test Executor 0'"], False), + ([b'java', main, b"'Gradle Test Executor -3'"], False), + ([b'java', main, b"'Gradle Test Executor 3\n'"], False), + ([b'java', main + b'Extra', label], False), + ([b'java', b'-Dmain=' + main, label], False), + ([b'java', main, b'unrelated', label], False), + ([*valid, b'extra'], False), + ([b'java', b'@/unreadable/launch'], False), + ([b'java', b'-Dsecret=' + b'x' * 8192, main, label], False), + ] + with patch.object(CAPTURE, 'PROC_ROOT', proc): + for index, (argv, accepted) in enumerate(cases): + with self.subTest(case=index): + (base / 'cmdline').write_bytes(b'\0'.join(argv) + b'\0') + result = CAPTURE.java_identity(123) + self.assertEqual(accepted, result is not None) + if result: + self.assertEqual('test-worker', result['role']) + self.assertNotIn('argv', result) + self.assertNotIn('classpath', json.dumps(result)) + def test_stall_coverage_distinguishes_no_children_from_no_attribution(self): daemon = self.stall_identity() coverage = {} @@ -374,8 +414,8 @@ def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): observer.observe.assert_called_once_with(b'original output\n') observer.close.assert_called_once() - def test_module_wrapper_serializes_only_numbered_account_checks_including_fallback(self): - for module, partition, expected in [('account-service', '4', [2, 1]), + def test_module_wrapper_uses_two_workers_including_fallback(self): + for module, partition, expected in [('account-service', '4', [2, 2]), ('account-service', 'full', [2]), ('game-session-service', '4', [2, 2]), ('world-management-service', 'full', [2])]: diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index e5c6189fb1..399954a797 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -97,11 +97,16 @@ def reject(reason): arguments = stream.read(8193) if len(arguments) > 8192: return reject('command-line-limit') - arguments = arguments.split(b'\0') + arguments = arguments.removesuffix(b'\0').split(b'\0') if b'org.gradle.launcher.daemon.bootstrap.GradleDaemon' in arguments: role = 'daemon' - elif (b'worker.org.gradle.process.internal.worker.GradleWorkerMain' in arguments - and any(arg.startswith(b'Gradle Test Executor ') for arg in arguments)): + # Gradle 9.8.2 DefaultWorkerProcessBuilder.build adds literal single + # quotes around the display-name argument (these are not shell quoting). + # Require the complete trailing main/display pair, not an arbitrary argv + # substring. Unknown launch shapes remain unselected; never read argfiles. + elif (len(arguments) >= 3 + and arguments[-2] == b'worker.org.gradle.process.internal.worker.GradleWorkerMain' + and re.fullmatch(rb"'Gradle Test Executor [1-9][0-9]*'", arguments[-1])): role = 'test-worker' else: return reject('unrecognized-java-role') From c6ba6da55e6cc34f248c2e9a465f755c29abd2a1 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 09:50:41 +1300 Subject: [PATCH 51/66] fix(test): avoid nested locking read in JOIN expiry callback --- .../AccountApplicationIntegrationTest.java | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) 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 794c7249cf..21460ae893 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 @@ -744,18 +744,23 @@ void publicJoinExpiryDuringProcessingPreservesPendingIntentAndRollsBack(boolean String token = f.browserScope(); String request = UUID.randomUUID().toString(); var intent = new java.util.concurrent.atomic.AtomicReference(); - Runnable expire = - () -> { - intent.set(f.operation(request).intentDigest()); - f.clock.offset = Duration.ofMinutes(3); - }; if (duringProvider) { - f.paid.transport().duringRead(expire); + f.paid + .transport() + .duringRead( + () -> { + intent.set(f.operation(request).intentDigest()); + f.clock.offset = Duration.ofMinutes(3); + }); } else { org.mockito.Mockito.doAnswer( invocation -> { - var result = invocation.callRealMethod(); - expire.run(); + var result = + (AccountJoinOperationRepository.CanonicalJoinOperationEvidence) + invocation.callRealMethod(); + // Reuse the owner receipt: a new transaction would wait on the owner's locks. + intent.set(result.intentDigest()); + f.clock.offset = Duration.ofMinutes(3); return result; }) .when(f.operations) From 60f708c0e26466ce4aeaefe4bae1f399cab5b227 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 10:33:39 +1300 Subject: [PATCH 52/66] Use database time for hosting dispatch fences and clarify receiving boundaries --- .../account-service/runtime-and-data.md | 6 +- .../player-access-and-session.md | 8 +- ...ostingSubscriptionLifecycleRepository.java | 27 +-- ...g_subscription_first_provider_dispatch.sql | 9 +- ...nDispatchClockPostgresIntegrationTest.java | 173 ++++++++++++++++++ ...ngSubscriptionLifecycleRepositoryTest.java | 9 +- .../service/impl/AccountGrpcServiceTest.java | 54 ++++++ 7 files changed, 264 insertions(+), 22 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 40a9cc18ea..fe28cf005a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -95,8 +95,8 @@ Local unregistered Account owners now cover tenant-creation intent, admission, c Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile events and membership creation or restoration through `JoinPublicProductionMembership` use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a JOIN that creates or restores membership records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. An existing ACTIVE member commits `ALREADY_ACTIVE` without a new audit/outbox row. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and explicit JOIN membership creation or restoration append immutable Account audit envelopes in their respective local transactions. The `ALREADY_ACTIVE` outcome commits without a new audit row. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work; for membership creation or restoration, policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and explicit JOIN membership creation or restoration use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). @@ -316,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#grpc-apis). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences 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 4842208e7a..b46577548c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -PR #3390 currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-canonical-play-transition-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for labeled nonproduction cutover PR merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. +The canonical Account cutover currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-canonical-play-transition-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for labeled nonproduction cutover PR merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. ### Temporary canonical PLAY transition exception -The existing canonical-cutover stack may opt into the [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) with the `canonical-play-transition` label. The live PR must carry it; PR-event producers also require the event label, while typed base-refresh producers use the verified live PR label and exact current tuple. Typed-refresh support requires the updated producer workflow on the default branch and fresh evidence; it cannot qualify an earlier failed run without the marker. This includes #3390 and, only if deliberately labeled, dependent #3405, #3409, #3407, #3408 and #3410; #3403 is not approved for the exception and must remain unlabeled. This PR list records the approved operational scope, not a workflow PR-number allowlist: applying the label is the workflow scope control, and maintainers must limit it to these approved cuts. The workflow independently checks repository, event, exact PR tuple, classified failure, qualification and cleanup. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. +The explicitly approved nonproduction canonical-cutover scope has a [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), gated by the `canonical-play-transition` label and fresh evidence for the exact current PR tuple. The label does not authorize expanding that approved scope. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. ### Direct-text scope and JOIN identifier cutover @@ -22,9 +22,9 @@ Selected client-wire and Account receiver tests exercise these contracts separat This is an intentionally breaking preproduction format cutover of the manually composed, currently unregistered lobby. No production rollback or migration compatibility is claimed. Numeric-era retained scope/JOIN bytes are not supported by the canonical UUID decoder; the existing SQL retention and exact-original identity guards remain unchanged. Repository inspection establishes no runtime registration and supplies no inventory of deployed rows. Existing-data verification belongs to future runtime wiring or activation, not a new merge gate or slicing requirement for this PR: before reusing any database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. If it does, preserve that evidence and resolve its retention and recovery requirements before invoking the new owner against it; neither this cutover nor the temporary CI exception authorizes deletion, identity rewriting or retention bypass. Fresh component fixtures do not prove historical compatibility. -### Receiving review boundaries +### Canonical receiving capability boundaries -PR #3389 now carries the independent Account source/transport foundation on the supported `develop` runtime. Its unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery do not replace live PLAY authority. This draft PR #3390 retains canonical UUID schema retirement, the public facade/JOIN receiving cutover, the schema/retention foundation and focused owner units; provider-write execution and expanded dependent physical proof move to the immediate successor; it remains unfinished until a functioning canonical PLAY replacement is qualified. PR #3403 retains private FRESH/World preparation. The source and prior corrections remain preserved through normal ancestry; the changed comparisons do not reset review counts or grant current coverage. No new caller custody, runtime registration, admission or activation is established by the reconstruction. +The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, the schema/retention foundation and focused owner units. Provider-write execution, expanded physical proof and private FRESH/World preparation remain separate receiving obligations. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. ### Controlled player-admission transport composition diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 4ce8feca92..edd338b5fa 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -434,15 +434,16 @@ public Preparation prepare( : dsl.fetchOne( "SELECT claimed_at FROM subscription_provisioning_attempts WHERE attempt_id = ?", provisioningAttemptId); + Instant provisioningNow = databaseNow(); if (provisioningAttemptId == null || !"provisioning".equals(current.status()) || claimedAttempt == null - || now.isBefore(instant(claimedAttempt, "claimed_at")) + || provisioningNow.isBefore(instant(claimedAttempt, "claimed_at")) || !"CLAIMED".equals(work.get("phase", String.class)) || !provisioningAttemptId.equals(work.get("last_attempt_id", UUID.class)) || current.rowVersion() != work.get("subscription_row_version", Long.class) - || !now.isBefore(instant(work, "lease_expires_at")) - || !now.isBefore(instant(work, "deadline_at"))) { + || !provisioningNow.isBefore(instant(work, "lease_expires_at")) + || !provisioningNow.isBefore(instant(work, "deadline_at"))) { throw new FenceRejectedException( "Initial confirmation lacks its exact durable provisioning claim"); } @@ -933,6 +934,11 @@ private AccountHostingSubscriptionLifecyclePolicy retainedPolicy(Record operatio Duration.ofMillis(operation.get("grace_millis", Long.class)))); } + /** Provisioning leases and dispatch fences share PostgreSQL time, not the observation clock. */ + private Instant databaseNow() { + return instant(Objects.requireNonNull(dsl.fetchOne("SELECT clock_timestamp() AS now")), "now"); + } + private Instant now() { return clock.instant().truncatedTo(ChronoUnit.MICROS); } @@ -1217,10 +1223,6 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId prior == null ? expectedRowVersion : prior.get("claimed_row_version", Long.class); var current = intents.lockForProvisioningRecovery(requestId, versionToLock); var original = intents.findCreation(requestId).orElseThrow(); - Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); - if (now.isBefore(original.createdAt())) { - throw new FenceRejectedException("Provisioning clock predates the durable intent"); - } dsl.execute( "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " @@ -1234,6 +1236,10 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId utc(original.createdAt().plus(limits.absoluteTimeout())), utc(original.createdAt())); Record work = workForUpdate(requestId); + Instant now = databaseNow(); + if (now.isBefore(original.createdAt())) { + throw new FenceRejectedException("Provisioning clock predates the durable intent"); + } if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { return new ClaimResult(Disposition.TERMINAL_FAILURE, null); } @@ -1333,15 +1339,14 @@ public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID "INSERT INTO subscription_provider_dispatch_claim " + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, classification, " + "first_attempt_id, first_claimed_row_version, recorded_at) " - + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, clock_timestamp()) " + "ON CONFLICT (creation_request_id) DO NOTHING", original.requestId(), original.subscriptionId(), original.subscriptionProvisioningRequestId(), dispatchId, retained.attemptId(), - retained.subscriptionRowVersion(), - utc(now())); + retained.subscriptionRowVersion()); DispatchReceipt receipt = dispatchReceipt(original.requestId()); requireDispatchBinding(retained, receipt); boolean initial = @@ -1557,7 +1562,7 @@ public Disposition deferUnresolved(ProvisioningClaim claim) { intents.lockForProvisioningRecovery( claim.creation().requestId(), claim.subscriptionRowVersion()); Record work = workForUpdate(claim.creation().requestId()); - Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); + Instant now = databaseNow(); if (now.isBefore(claim.claimedAt())) { throw new FenceRejectedException("Provisioning clock predates its retained claim"); } diff --git a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql index 177f4527d5..f5884ad7cc 100644 --- a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql +++ b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql @@ -39,6 +39,7 @@ DECLARE attempt subscription_provisioning_attempts%ROWTYPE; instrument payment_instrument%ROWTYPE; customer billing_customer%ROWTYPE; + dispatch_at TIMESTAMPTZ; BEGIN SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; PERFORM 1 FROM accounts WHERE account_uuid = creation.account_uuid FOR UPDATE; @@ -48,6 +49,9 @@ BEGIN SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = creation.subscription_id FOR UPDATE; SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = creation.request_id FOR UPDATE; SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = NEW.first_attempt_id; + -- Sample after every potentially blocking owner lock. A caller timestamp or transaction-start + -- timestamp cannot prove that the original lease is still live at the dispatch boundary. + dispatch_at := clock_timestamp(); IF NEW.classification <> 'FIRST_DISPATCH' OR NEW.subscription_id <> creation.subscription_id OR NEW.provider_operation_id <> creation.subscription_provisioning_request_id @@ -65,10 +69,11 @@ BEGIN OR instrument.provider_customer_id <> creation.provider_customer_id OR customer.state <> 'CONFIRMED' OR customer.provider_customer_id <> creation.provider_customer_id OR customer.customer_provisioning_request_id <> creation.customer_provisioning_request_id - OR NEW.recorded_at < attempt.claimed_at OR NEW.recorded_at >= attempt.expires_at - OR NEW.recorded_at >= work.deadline_at THEN + OR dispatch_at < attempt.claimed_at OR dispatch_at >= attempt.expires_at + OR dispatch_at >= work.deadline_at THEN RAISE EXCEPTION 'Provider dispatch lacks exact live original provisioning fence' USING ERRCODE = '23514'; END IF; + NEW.recorded_at := dispatch_at; RETURN NEW; END; $$; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java new file mode 100644 index 0000000000..5c7a518e5c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture.Fixture; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL clock/locks; controlled enrollment only, with no provider calls or registration. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountHostingSubscriptionDispatchClockPostgresIntegrationTest { + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @ParameterizedTest + @ValueSource(ints = {-365, 365}) + void claimAndFirstDispatchUseDatabaseTimeDespiteObservationClockSkew(int skewDays) { + Fixture f = fixture(); + var owner = owner(f, Duration.ofSeconds(10), Duration.ofHours(1), skewDays); + Instant before = databaseNow(f); + var claim = + Objects.requireNonNull( + f.transaction() + .execute(s -> owner.claim(f.creation().requestId(), 1, UUID.randomUUID()))) + .claim(); + assertThat(claim.claimedAt()).isBetween(before, databaseNow(f)); + assertThat(claim.expiresAt()).isEqualTo(claim.claimedAt().plusSeconds(10)); + + var prepared = + f.transaction().execute(s -> owner.prepareProviderDispatch(claim, UUID.randomUUID())); + var read = + Objects.requireNonNull(f.transaction().execute(s -> owner.readProviderDispatch(prepared))); + assertThat(read.readyForProviderIo()).isTrue(); + assertThat(read.initialCallAllowed()).isTrue(); + Instant recorded = + Objects.requireNonNull( + f.dsl().fetchOne("SELECT recorded_at FROM subscription_provider_dispatch_claim")) + .get("recorded_at", OffsetDateTime.class) + .toInstant(); + assertThat(recorded).isBetween(claim.claimedAt(), databaseNow(f)); + assertThat(recorded).isBefore(claim.expiresAt()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void backdatedDispatchCannotConsumeFirstPermissionAfterActualDatabaseExpiry( + boolean absoluteDeadline) { + Fixture f = fixture(); + var owner = + owner( + f, + absoluteDeadline ? Duration.ofSeconds(5) : Duration.ofSeconds(3), + absoluteDeadline ? Duration.ofSeconds(5) : Duration.ofHours(1), + 0); + var claim = + Objects.requireNonNull( + f.transaction() + .execute(s -> owner.claim(f.creation().requestId(), 1, UUID.randomUUID()))) + .claim(); + assertThat(claim).isNotNull(); + if (absoluteDeadline) { + assertThat(claim.expiresAt()).isEqualTo(f.creation().createdAt().plusSeconds(5)); + } + // Retain the same timestamp the old application-clock INSERT could sample while still live. + // Start this transaction before expiry, then wait on PostgreSQL time. Neither transaction time + // nor the caller's earlier recorded_at is a valid substitute for the trigger's late clock read. + Instant sampled = databaseNow(f); + assertThat(sampled).isBefore(claim.expiresAt()); + assertThatThrownBy( + () -> + f.transaction() + .executeWithoutResult( + s -> { + assertThat(databaseNow(f)).isBefore(claim.expiresAt()); + f.dsl() + .execute( + "SELECT pg_sleep_until(?::timestamptz)", + claim.expiresAt().plusMillis(5).atOffset(ZoneOffset.UTC)); + assertThat(databaseNow(f)).isAfterOrEqualTo(claim.expiresAt()); + f.dsl() + .execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " + + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", + f.creation().requestId(), + f.creation().subscriptionId(), + f.creation().subscriptionProvisioningRequestId(), + UUID.randomUUID(), + claim.attemptId(), + claim.subscriptionRowVersion(), + sampled.atOffset(ZoneOffset.UTC)); + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence") + .satisfies( + failure -> assertThat(((DataAccessException) failure).sqlState()).isEqualTo("23514")); + assertThat(f.dsl().fetchCount(org.jooq.impl.DSL.table("subscription_provider_dispatch_claim"))) + .isZero(); + var replay = + Objects.requireNonNull( + f.transaction() + .execute(s -> owner.claim(f.creation().requestId(), 1, claim.attemptId()))); + assertThat(replay.disposition()).isEqualTo(Disposition.ATTEMPT_EXPIRED); + assertThat(replay.claim()).isNull(); + assertThat(f.transaction().execute(s -> owner.deferUnresolved(claim))) + .isEqualTo(absoluteDeadline ? Disposition.TERMINAL_FAILURE : Disposition.ATTEMPT_EXPIRED); + } + + private static AccountHostingSubscriptionLifecycleRepository owner( + Fixture f, Duration lease, Duration timeout, int skewDays) { + return new AccountHostingSubscriptionLifecycleRepository( + f.dsl(), + f.intents(), + skewDays == 0 + ? Clock.systemUTC() + : Clock.fixed(f.creation().createdAt().plus(Duration.ofDays(skewDays)), ZoneOffset.UTC), + new ReconciliationLimits(4, 3, lease, Duration.ofMillis(1), timeout), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + } + + private static Instant databaseNow(Fixture f) { + return Objects.requireNonNull(f.dsl().fetchOne("SELECT clock_timestamp() AS now")) + .get("now", OffsetDateTime.class) + .toInstant(); + } + + private static Fixture fixture() { + String schema = "dispatch_clock_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .load() + .migrate(); + Fixture f = CanonicalHostingSubscriptionTestFixture.create(source); + f.transaction().setTimeout(10); + return f; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 3d6f9cb464..19b9f00349 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -78,7 +78,7 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( new AccountHostingSubscriptionLifecycleRepository( dsl, controlledIntents, - Clock.fixed(expiresAt.plusSeconds(secondsAfterExpiry), ZoneOffset.UTC), + Clock.fixed(expiresAt.minusSeconds(5), ZoneOffset.UTC), limits(3, 2, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), new AccountHostingSubscriptionLifecyclePolicy( Duration.ofSeconds(15), @@ -102,14 +102,19 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( String lockedWorkSql = "SELECT * FROM subscription_provisioning_work WHERE request_id = ? FOR UPDATE"; when(dsl.fetchOne(lockedWorkSql, requestId)).thenReturn(retainedWork); + var databaseClock = mock(Record.class); + when(databaseClock.get("now", OffsetDateTime.class)) + .thenReturn(expiresAt.plusSeconds(secondsAfterExpiry).atOffset(ZoneOffset.UTC)); + when(dsl.fetchOne("SELECT clock_timestamp() AS now")).thenReturn(databaseClock); TransactionSynchronizationManager.setActualTransactionActive(true); assertThat(controlledRepository.deferUnresolved(claim)).isEqualTo(Disposition.ATTEMPT_EXPIRED); - // Exactly the owner/retained-work locks are allowed: no SQL writes, intent settlement, + // Only owner/retained-work locks and the database clock are read: no SQL writes, settlement, // reservation release, or replacement attempt can occur on this return. verify(controlledIntents).lockForProvisioningRecovery(requestId, 7L); verify(dsl).fetchOne(lockedWorkSql, requestId); + verify(dsl).fetchOne("SELECT clock_timestamp() AS now"); verifyNoMoreInteractions(controlledIntents, dsl); } 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 90bd7f50e3..cd31baed7d 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 @@ -608,6 +608,60 @@ void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmI Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource( + strings = { + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId" + }) + void directTextScopeRejectsMissingTargetFieldsEvenWhenCallerMatches(String field) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + var target = validScopeRequest().toBuilder(); + var caller = validPlayerContext().toBuilder(); + switch (field) { + case "tenantId" -> { + target.clearTenantId(); + caller.clearTenantId(); + } + case "realmId" -> { + target.clearRealmId(); + caller.clearRealmId(); + } + case "worldSlug" -> target.clearWorldSlug(); + case "realmSlug" -> target.clearRealmSlug(); + case "playableStateNamespaceId" -> { + target.clearPlayableStateNamespaceId(); + caller.clearPlayableStateNamespaceId(); + } + case "playableStateScope" -> { + target.clearPlayableStateScope(); + caller.clearPlayableStateScope(); + } + case "gameInstanceId" -> { + target.clearGameInstanceId(); + caller.clearGameInstanceId(); + } + default -> throw new IllegalArgumentException("Unknown target field: " + field); + } + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope(target.setPlayerContext(caller).build(), observer)); + + assertTrue(observer.completed()); + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(owner); + } + @ParameterizedTest @ValueSource( strings = { From 3fcb24ec07f965046317d5b283016c05e4664971 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 11:43:41 +1300 Subject: [PATCH 53/66] Bind temporary smoke exception to complete proof inputs --- .github/workflows/smoke.yml | 14 +++++++++++++- design/architecture/system-architecture-cicd.md | 4 ++-- .../tests/pr-required-gate-context-contract.sh | 13 ++++++++++++- ...untPlayerAdmissionSharedEntitlementFixture.java | 4 +++- 4 files changed, 30 insertions(+), 5 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e3a78ec365..681381a02e 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -609,10 +609,22 @@ jobs: // One canonical producer definition; the contract test reports fingerprint upkeep. const canonicalRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; + // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", "dev-tools/smoke/smoke_common.py": "a1e36948b500ac796295560cb8c22321ebe47eab78be9e1f4d58837053547534", - "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b" + "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b", + "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", + "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", + "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", + "dev-tools/smoke/run-owned-compose.sh": "c2a0590c98d39a8c8ec22c20e692948136a5ec53ca2dfc0b29db7323a3e1b6be", + "dev-tools/certs/ensure-dev-certs.sh": "30f4ab5c9cb7af7f9d4a477ce923cfad19a319a85b6e05957f7d24eae9baddd2", + ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", + "docker/docker-compose.yml": "f43581c67747dfb732742ecc1c4de631a71a2a41ae535663fb3872a90b68e2f1", + "docker/docker-compose.override.yml": "2e720be03f942fd4456d46cea5a127f16106a1056aec6ddaaf52b2bb31b51d75", + "docker/docker-compose.smoke-images.override.yml": "7717be8b49a1dc548a47fba852c181feeb4dbe9a21fc201a7f8e74b992801fd6", + "docker/docker-compose.pr-local-minio.override.yml": "d975ce211afcb73079a21c70fda358e3a8f3366b83fe0302907c9d7149ce965e", + "docker/docker-compose.grpc-mtls.override.yml": "dcee047f1492392035d57153ba8dfd6d38de33ca932d327f377440d5813577f0" }; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index a489a62e9e..7ca758de50 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,9 +88,9 @@ A typed runtime refresh hands off publication explicitly after its required cred The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers are always fingerprinted at the tested PR merge. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. -The step-independent producer guarantee is bound to one SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. This single fingerprint is part of the owning workflows, not a separate proof registry. +The step-independent producer guarantee is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. Branch-to-environment promotion contract: diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 2ec7a6300a..6926901890 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -526,13 +526,24 @@ classifier_paths = ( "dev-tools/verify-smoke-images.sh", "dev-tools/smoke/smoke_common.py", "services/game-session-service/websocket-login-look-smoke.sh", + "dev-tools/smoke/demo-smoke-defaults.sh", + "dev-tools/smoke/held-admission-qualification.sh", + "dev-tools/smoke/held_admission_qualification.py", + "dev-tools/smoke/run-owned-compose.sh", + "dev-tools/certs/ensure-dev-certs.sh", + ".env.sample", + "docker/docker-compose.yml", + "docker/docker-compose.override.yml", + "docker/docker-compose.smoke-images.override.yml", + "docker/docker-compose.pr-local-minio.override.yml", + "docker/docker-compose.grpc-mtls.override.yml", ) classifier_fingerprints = re.search(r"const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});", script) if classifier_fingerprints is None: raise SystemExit("Smoke Gate must fingerprint the canonical PLAY classifier files") classifiers = json.loads(classifier_fingerprints[1]) if set(classifiers) != set(classifier_paths): - raise SystemExit("Smoke Gate PLAY classifier fingerprint paths must match the three canonical files") + raise SystemExit("Smoke Gate PLAY classifier fingerprint paths must match the canonical classifier, qualification, cleanup, and configuration inputs") classifier_definitions = {} for path in classifier_paths: classifier_bytes = (root / path).read_bytes() diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java index 0040681212..64c6e0907d 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java @@ -389,7 +389,9 @@ public void assertAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence ev private void requireCurrentTarget(RealmScope issued, CanonicalJoinScopeV2 scope) { var selector = new RetainedTargetSelector( - UUID.randomUUID(), + UUID.nameUUIDFromBytes( + ("first-join-target-selector/v1:" + scope.connectScopeId()) + .getBytes(StandardCharsets.UTF_8)), scope.accountId(), namespace, scope.tenantId(), From aabf0e2c40f34e72667f39d04eb127d98973c3d1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 12:31:47 +1300 Subject: [PATCH 54/66] Qualify browser world discovery by tenant selectors --- .../account-service/api-contracts.md | 26 +++++++---- .../system-architecture-authentication.md | 14 +++--- .../system-architecture-frontend.md | 4 +- design/product/user-journeys/players.md | 4 +- .../player-access-and-session.md | 4 +- .../run-player-experience-smoke.py | 21 ++++++++- ...player-experience-smoke-runner-contract.sh | 28 +++++++++++ .../controller/AuthController.java | 6 ++- .../accountservice/dto/BootstrapWorldDto.java | 4 +- .../AccountPublicBootstrapWorldsOwner.java | 21 +++------ .../service/AccountService.java | 3 +- .../service/impl/AccountServiceImpl.java | 5 +- .../src/main/resources/openapi.yaml | 12 ++++- .../AccountApplicationIntegrationTest.java | 5 +- ...rUuidEntityCompositionIntegrationTest.java | 7 ++- ...emoWorldsOwnerPostgresIntegrationTest.java | 8 ++-- .../controller/AuthControllerTest.java | 16 ++++++- ...AccountPublicBootstrapWorldsOwnerTest.java | 13 ++++-- .../service/impl/AccountServiceImplTest.java | 46 ++++++++++++------- .../LegacySubscriptionContainmentTest.java | 1 + 20 files changed, 171 insertions(+), 77 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 71ac40c49a..3fff9c7097 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -99,13 +99,15 @@ At effective expiry or revocation, Account publishes the monotonic grant-authori ### Public bootstrap WORLDS discovery -`ListBootstrapWorlds` returns the complete set of unambiguous visible public-production worlds whose current Account entitlement says gameplay is available. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug` ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). +Each visible world returns its stable `tenantSlug` and tenant-scoped `worldSlug` with its display name. Different tenants may expose the same world slug; clients retain both selectors and pass `tenantSlug` as the required query parameter to `GET /auth/bootstrap/worlds/{worldSlug}/realms`. Account resolves the pair against one complete current discovery collection. A bare or globally inferred world selector is not a supported browser request. The resulting opaque `connectScopeId` binds the exact tenant and realm for subsequent character discovery and admission; the character route still verifies its world/realm path against that scope. + +`ListBootstrapWorlds` returns the complete set of unambiguous visible public-production worlds whose current Account entitlement says gameplay is available. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug`, then `tenantSlug`, ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Independent tenant entitlement evaluations run outside ambient SQL with at most eight concurrent workers per discovery request. A shared fair eight-permit bound also limits active evaluations across all discovery requests and owner instances in the Account process. Waiting for a permit occurs outside SQL and lasts at most five seconds; contention expiry fails the whole discovery request as `ENTITLEMENT_UNAVAILABLE`. Success, source failure and interruption return acquired permits. This bounds this owner’s aggregate connection demand without resizing the Account pool or guaranteeing production capacity. Each tenant is evaluated once and retains its owner’s independent transaction/isolation checks; caller and SQL context are not propagated to workers. The owner waits for the complete set, validates every returned tenant identity and returns no partial result on failure or interruption. Original observation deadlines remain unchanged and are checked after the second complete target read and final caller check. This bound reduces serialized latency; it is not a production capacity guarantee or permission to extend expired evidence, and slow or large collections can still refuse when their original observations expire. An unreachable Game Session authority maps to `AUTH_UNAVAILABLE`; a reachable malformed, ambiguous, or changed collection maps to `ADMISSION_POINTER_UNAVAILABLE`; and an unavailable or expired entitlement maps to `ENTITLEMENT_UNAVAILABLE`. Bootstrap-caller verification retains its authentication failure. None of these failures produces an empty or partial success. -`gameplayAvailable` controls discovery visibility; `allowPublicJoin` does not. This pre-scope result contains only world slug and display name and creates no membership, JOIN, connect scope, or gameplay-admission authority. Public bootstrap discovery does not resolve private playtest realms or substitute for later target selection, current entitlement, membership, grant, or admission checks. +`gameplayAvailable` controls discovery visibility; `allowPublicJoin` does not. This pre-scope result contains only tenant slug, world slug and display name and creates no membership, JOIN, connect scope, or gameplay-admission authority. Public bootstrap discovery does not resolve private playtest realms or substitute for later target selection, current entitlement, membership, grant, or admission checks. The manually composed `AccountCanonicalPublicRealmScopeOwner` uses the same public source collection for UUID-bearing V2 selector scopes. It rechecks Account identity, fresh tenant provenance, current membership and billing-head observations in short Account transactions, retains the exact signed scope preimage and verifies its immutable readback. Protected Game Session, registry and provider reads stay outside those transactions. Scope expiry follows the configured scope lifetime capped by the original verified bootstrap expiry; a later check cannot restamp an expired observation. Public visibility remains membership-independent, while current membership and `allowPublicJoin` are facts for subsequent fresh selection and JOIN checks. The scope grants neither membership repair nor gameplay admission. This source is manually composed by the public UUID facades but remains unregistered and separate from the private-realm path; its proof and receiving gaps are recorded in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). @@ -141,8 +143,6 @@ Account UUID generation currently has three established provenances: `ACCOUNT_RE This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. -Current explicit JOIN status: with the default composition absent, Account's `JoinPublicProductionMembership` service method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, the service method proceeds into scope/target validation and authority reads; the gRPC adapter can still refuse peer or request-shape failures before the service call. This does not establish default runtime exposure or qualified live JOIN. The Gateway route remains blocked by its guard and absent from `publicOpenAPI`. The held boundary, preserved positive obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); target JOIN authority and commit requirements remain in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). - `ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. Explicit playtest grants remain partial: registered Account persistence and internal lookup retain the legacy four-field identity. Unregistered lifecycle-bound storage and its current-lifecycle read retain explicit expiry bounded by fork expiry, request-idempotent outcomes and revocation tombstones. Registered management and consumer entry points, tenant-admin create/extend/list/revoke, distinct audited platform break-glass mutation, qualified actor authorization and active-binding ejection remain incomplete or unproved. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#lifecycle-bound-private-realm-grant-source-preparation) records the local proof and remaining gaps. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. @@ -151,7 +151,13 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. With the default composition absent, `JoinPublicProductionMembership` returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into validation and authority reads; the gRPC adapter may refuse peer or request-shape failures before the service call. The Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. With canonical scope consumers absent, current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When consumers are manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/grant/pointer reads, token minting, or replay/session mutation. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. 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 obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain 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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. JOIN receiver availability and its blocked Gateway route are recorded under [Current Receiver Composition](#current-receiver-composition). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. 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 obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. + +### Current Receiver Composition + +Current explicit JOIN status: with the default composition absent, Account's `JoinPublicProductionMembership` service method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, the service method proceeds into scope/target validation and authority reads; the gRPC adapter can still refuse peer or request-shape failures before the service call. This does not establish default runtime exposure or qualified live JOIN. The Gateway route remains blocked by its guard and absent from `publicOpenAPI`. The held boundary, preserved positive obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); target JOIN authority and commit requirements remain in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). + +With canonical scope consumers absent, current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When consumers are manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/grant/pointer reads, token minting, or replay/session mutation. ### Account Tenant Identifier Boundary @@ -375,7 +381,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. Account's local creation protection covers the current authenticated player's membership, applicable realm grant, and entitlement authority; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection) for the cross-owner terminal boundary. | -| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** A prepared Account `JoinPublicProductionMembership` component implements explicit public-production membership creation. With the default composition absent, the service method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable; when manually configured, it proceeds into validation and authority reads, while the gRPC adapter may refuse peer or request-shape failures before the service call. Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | +| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** A prepared Account `JoinPublicProductionMembership` component implements explicit public-production membership creation. See [Current Receiver Composition](#current-receiver-composition) for receiver availability. Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | | `POST` | `/tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | **Target-state only; not currently routable.** Target duplicate-safe create-or-extend surface. The body carries the exact `accountId`, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision` (absent-grant precondition for `CREATE`, required current revision for `EXTEND`); exact `mutationDigest/v1` retries replay the stored outcome and changed intent or revision returns `IDEMPOTENCY_CONFLICT` or `GRANT_REVISION_CONFLICT` as defined above. | @@ -386,8 +392,8 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** `accountId` is the canonical lowercase non-nil Account UUID. Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route remains implementation drift and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current default composition:** absent canonical scope consumers, Account returns `AUTH_UNAVAILABLE` before bootstrap or connect-scope validation. With consumers manually configured, `issueConnectToken` validates the bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation; the held boundary and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** With the default composition absent, the current Account receiving method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, it proceeds into scope/target validation and authority reads; gRPC peer/shape checks can refuse before the service call. The Gateway path remains blocked by its explicit route guard. Current status, preserved obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. This terminates the call while preserving the existing `PENDING` or terminal receipt state; it does not authorize rewriting that state or retrying with expired authority. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. See [Current Receiver Composition](#current-receiver-composition) for the current held issuance boundary. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** The Gateway path remains blocked; see [Current Receiver Composition](#current-receiver-composition) for the service and adapter boundary. The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. This terminates the call while preserving the existing `PENDING` or terminal receipt state; it does not authorize rewriting that state or retrying with expired authority. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -402,7 +408,7 @@ The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountI 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. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. **Current default composition:** with canonical scope consumers absent, Account returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When manually configured, `issueConnectToken` validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, token minting, or replay/session mutation. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; no gRPC `IssueConnectToken` transport exists. +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. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. See [Current Receiver Composition](#current-receiver-composition) for the held issuance boundary. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; 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. @@ -436,7 +442,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/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | 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 ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. With default compositions absent, the Account world/realm/character discovery, direct-scope, JOIN, and connect-token receivers fail closed with `AUTH_UNAVAILABLE`; manually configured direct-scope and JOIN owners proceed into their applicable validation and authority reads, while configured connect-token validates bootstrap identity and reads the connect scope before its subsequent `AUTH_UNAVAILABLE`; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. With canonical scope consumers absent, current `POST /auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before membership/entitlement/admission-pointer or cached-result reads, or token minting. 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. Target success delivery uses only 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. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | +| 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 ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. Default discovery remains unavailable; JOIN and connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. 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. Target success delivery uses only 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. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | 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. | diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index d89d377b00..9d61684ca2 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -418,9 +418,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "demo", worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/demo/realms +GET /auth/bootstrap/worlds/demo/realms?tenantSlug=demo Authorization: Bearer -> [{ worldSlug: "demo", @@ -465,9 +465,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "emberfall", displayName: "Emberfall" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "emberfall-studio", worldSlug: "emberfall", displayName: "Emberfall" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/emberfall/realms +GET /auth/bootstrap/worlds/emberfall/realms?tenantSlug=emberfall-studio Authorization: Bearer -> [{ worldSlug: "emberfall", @@ -488,7 +488,7 @@ Authorization: Bearer { connectScopeId: "cs_emberfall_production_v1", requestId: "req-join-1" } -> { tenantId: "e14f2d0c-8b7a-4f26-9c51-6a3d7e8b2c40", membershipExists: true, membershipLifecycleState: "ACTIVE", roles: ["player"], gameplayAdmissionAllowed: true, membershipAuthorityGeneration: 8, membershipVersion: 1, authorityTuple: { issuerAuthGeneration: 7, accountAuthorityGeneration: 12, tenantAuthorityGeneration: { "e14f2d0c-8b7a-4f26-9c51-6a3d7e8b2c40": 4 }, membershipAuthorityGeneration: { "e14f2d0c-8b7a-4f26-9c51-6a3d7e8b2c40": 8 }, privateRealmGrantVersions: [] }, evaluatedAt: "2026-08-02T00:00:00Z", outboxCheckpoints: [{ outboxStreamKey: "account:auth-authority:v1:membership//", outboxSequence: 1 }], joined: true } -GET /auth/bootstrap/worlds/emberfall/realms +GET /auth/bootstrap/worlds/emberfall/realms?tenantSlug=emberfall-studio Authorization: Bearer -> [{ worldSlug: "emberfall", @@ -548,9 +548,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "demo", worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/demo/realms +GET /auth/bootstrap/worlds/demo/realms?tenantSlug=demo Authorization: Bearer -> [ { diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 1c61352bf7..e8f90660fb 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -170,9 +170,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "demo", worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/demo/realms +GET /auth/bootstrap/worlds/demo/realms?tenantSlug=demo Authorization: Bearer -> [{ worldSlug: "demo", diff --git a/design/product/user-journeys/players.md b/design/product/user-journeys/players.md index 50659a67c6..5ce40e9026 100644 --- a/design/product/user-journeys/players.md +++ b/design/product/user-journeys/players.md @@ -130,7 +130,7 @@ Example first-party web flow for a returning member or grant-backed target: ```text POST /auth/player-bootstrap { accountIdentifier=player@example.com, secret= } GET /auth/bootstrap/worlds -GET /auth/bootstrap/worlds/{world}/realms +GET /auth/bootstrap/worlds/{world}/realms?tenantSlug={tenantSlug} GET /auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope} POST /auth/connect-token { connectScopeId=cs_demo_production_v17 } GET /ws/game/** with the Firemud-Connect-Token cookie set by the previous response @@ -143,7 +143,7 @@ Target-state example first-time public production join (explicit `JOIN`/`Join & ```text POST /auth/player-bootstrap { accountIdentifier=player@example.com, secret= } GET /auth/bootstrap/worlds -GET /auth/bootstrap/worlds/emberfall/realms +GET /auth/bootstrap/worlds/emberfall/realms?tenantSlug=emberfall-studio POST /auth/bootstrap/join { connectScopeId=cs_emberfall_production_v1, requestId=req-join-1 } GET /auth/bootstrap/worlds/emberfall/realms/production/characters?connectScopeId=cs_emberfall_production_v1 POST /auth/bootstrap/worlds/emberfall/realms/production/characters { connectScopeId=cs_emberfall_production_v1, createCharacterRequestId=char-create-1, name=Mara, descriptorId=emberfall-human-fighter, descriptorVersion=17 } 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 b46577548c..5340479c96 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -62,13 +62,15 @@ Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 ### Public bootstrap WORLDS source preparation +The browser selector correction preserves tenant-scoped world-slug reuse end to end: WORLDS carries `tenantSlug`, REALMS requires it with `worldSlug`, and the facade uses the existing qualified selector owner. The player-experience smoke caller requires `PLAYER_EXPERIENCE_TENANT_SLUG` rather than inferring a global world. Focused proof passes all 414 selected Account controller, facade, WORLDS, REALMS and containment cases with zero failures, errors or skips using an explicit cached Mockito startup agent because this local JDK cannot self-attach. Smoke-runner and architecture contracts, local links and Markdown checks pass. Account integration-source compilation and enabled Java formatting also pass; registered-runtime and physical database qualifications below are unchanged. See the [Account selector contract](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery). + Paid discovery activation requires a composed durable webhook-driven or periodic lifecycle-reconciliation producer that commits a new Account receipt for each verified provider renewal period. The local `reconcile` entry point is implemented, but no such automatic producer is registered or qualified here. A renewal changes provider period facts and expires the prior positive bound; the current read intentionally refuses rather than extending or reinterpreting that immutable receipt. Until the new receipt is committed, a visible paid tenant can therefore make the complete WORLDS collection return `ENTITLEMENT_UNAVAILABLE`. The provider-reconciliation and registration prerequisite remains open under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract) and [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#subscriptions-and-hosting-plans); component read proof does not qualify paid discovery activation. The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required. Proof396 passes 46 front policy/repository/service and Game Session discovery cases with enabled affected analysis, formatting and documentation checks. Proof397 passes 20 discovery/entitlement units and 27 physical lifecycle/terminal cases, including delayed provider-confirmed and effective-cancellation negative reads, stale/changed provider refusal and unchanged receipt/authority rows including xmin. The bounded shared-cause check covers every implemented hosting status and both paid/DEMO discovery branches: proof399 passes 37 physical lifecycle, terminal-recovery and DEMO cases, including delayed suspended reads and real grace/period cutoffs; proof400 passes four tenant-operation owner cases with a fresh SDK evaluation after the original observation window and stable committed snapshot identity. All have zero failures, errors or skips and enabled affected checks. TENANT_OPERATION remains an as-of, non-admitting source observation; this does not add currentness protection, capacity authority or default registration. The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. Proof392 passes all 26 selected physical cases: 21 lifecycle cases and five genuine terminal-recovery compositions, with no failures, errors or skips, plus enabled integration analysis, formatting and documentation checks. The delayed active/trialing reads use new real SDK observations after the original observation window, retain the original receipt and authority rows including xmin, and append no events; stale reads, changed facts, actual period and recovery boundaries still refuse. Proof390 separately passes 32 front policy/repository/service and Game Session published-read cases with enabled affected analysis and documentation checks. Proof389 failed compilation and proof391 failed a public-versus-private error-message assertion; both are retained and corrected. The front carrier does not contain the V1028–V1032 schema foundation and takes this physical qualification from the canonical receiver. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. -[`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. +[`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug then tenant slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. Independent tenant entitlement evaluations now overlap, with shared resource bounds across concurrent requests and owner instances under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery). The implementation preserves transaction isolation, exact tenant identity and original observation expiry. Production pool sizing, throughput and capacity remain unqualified. diff --git a/dev-tools/observability/run-player-experience-smoke.py b/dev-tools/observability/run-player-experience-smoke.py index 01ee59f1a0..f2924bd3bb 100644 --- a/dev-tools/observability/run-player-experience-smoke.py +++ b/dev-tools/observability/run-player-experience-smoke.py @@ -403,6 +403,7 @@ def __init__( username: str, password: str, world: str, + tenant_slug: str | None, timeout_seconds: int, startup_wait_seconds: int, external_authority_evidence: Path | None, @@ -439,6 +440,7 @@ def __init__( self.username = username self.password = password self.world = world + self.tenant_slug = tenant_slug self.timeout_seconds = timeout_seconds self.startup_wait_seconds = startup_wait_seconds self.external_authority_evidence = external_authority_evidence @@ -534,6 +536,7 @@ def from_env( username=os.environ.get("SMOKE_USERNAME", DEFAULT_SMOKE_USERNAME), password=os.environ.get("SMOKE_PASSWORD", DEFAULT_SMOKE_PASSWORD), world=os.environ.get("PLAYER_EXPERIENCE_WORLD", "demo"), + tenant_slug=os.environ.get("PLAYER_EXPERIENCE_TENANT_SLUG"), timeout_seconds=int(os.environ.get("SMOKE_TIMEOUT_SECONDS", "10")), startup_wait_seconds=int(os.environ.get("SMOKE_STARTUP_WAIT_SECONDS", "90")), external_authority_evidence=external_authority_evidence, @@ -2051,9 +2054,12 @@ def issue_player_bootstrap(config: SmokeConfig) -> dict[str, Any]: def resolve_connect_scope_id(config: SmokeConfig, bootstrap_token: str) -> str: + require_tenant_selector(config) response = http_request_json( public_auth_url( - config, f"/auth/bootstrap/worlds/{quote_path(config.world)}/realms" + config, + f"/auth/bootstrap/worlds/{quote_path(config.world)}/realms" + + "?" + urlencode({"tenantSlug": config.tenant_slug}) ), config.timeout_seconds, headers={"Authorization": f"Bearer {bootstrap_token}"}, @@ -2066,14 +2072,25 @@ def resolve_connect_scope_id(config: SmokeConfig, bootstrap_token: str) -> str: ) +def require_tenant_selector(config: SmokeConfig) -> None: + if not config.tenant_slug or not config.tenant_slug.strip(): + raise ProbeOperationalFailure( + "PLAYER_EXPERIENCE_TENANT_SLUG must select the world's tenant; world slugs are not global" + ) + + def require_visible_world(config: SmokeConfig, bootstrap_token: str) -> None: + require_tenant_selector(config) response = http_request_json( public_auth_url(config, "/auth/bootstrap/worlds"), config.timeout_seconds, headers={"Authorization": f"Bearer {bootstrap_token}"}, ) for world in response["data"]: - if world.get("worldSlug") == config.world: + if ( + world.get("worldSlug") == config.world + and world.get("tenantSlug") == config.tenant_slug + ): return raise ProbeOperationalFailure( f"World {config.world!r} was not visible during bootstrap discovery" diff --git a/dev-tools/tests/player-experience-smoke-runner-contract.sh b/dev-tools/tests/player-experience-smoke-runner-contract.sh index d79df6903f..f85d6fe308 100644 --- a/dev-tools/tests/player-experience-smoke-runner-contract.sh +++ b/dev-tools/tests/player-experience-smoke-runner-contract.sh @@ -35,6 +35,7 @@ SMOKE_CONFIG_ENV_UNSETS=( -u SMOKE_USERNAME -u SMOKE_PASSWORD -u PLAYER_EXPERIENCE_WORLD + -u PLAYER_EXPERIENCE_TENANT_SLUG -u SMOKE_TIMEOUT_SECONDS -u SMOKE_STARTUP_WAIT_SECONDS -u PLAYER_EXPERIENCE_AUTH_API_BASE @@ -82,6 +83,33 @@ assert env_config.telnet_transport is None assert env_config.telnet_server_hostname is None assert env_config.telnet_ca_file is None +# Browser world selection remains qualified even when another tenant reuses its slug. +assert env_config.tenant_slug is None +with patch.object(runner_module, "http_request_json") as request: + try: + runner_module.resolve_connect_scope_id(env_config, "bootstrap") + except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) + else: + raise AssertionError("Bare browser world selector was accepted") + request.assert_not_called() +with patch.dict("os.environ", {"PLAYER_EXPERIENCE_TENANT_SLUG": "tenant-b"}): + qualified = runner_module.SmokeConfig.from_env("contract-test", "websocket", None) +with patch.object(runner_module, "http_request_json", return_value={"data": [ + {"worldSlug": qualified.world, "tenantSlug": "tenant-a"} +]}) as request: + try: + runner_module.require_visible_world(qualified, "bootstrap") + except runner_module.ProbeOperationalFailure: + pass + else: + raise AssertionError("Another tenant's world satisfied discovery") +with patch.object(runner_module, "http_request_json", return_value={"data": [ + {"realmSlug": qualified.realm_slug, "connectScopeId": "qualified-scope"} +]}) as request: + assert runner_module.resolve_connect_scope_id(qualified, "bootstrap") == "qualified-scope" + assert request.call_args.args[0].endswith("/realms?tenantSlug=tenant-b") + runner_module.validate_telnet_transport_config( env_config, {"websocket"}, simulate=False ) 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 e51178229b..7b25dc31cc 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 @@ -73,10 +73,12 @@ public ResponseEntity>> listBootstrapWorlds( @GetMapping("/bootstrap/worlds/{worldSlug}/realms") public ResponseEntity>> listBootstrapRealms( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, - @PathVariable String worldSlug) { + @PathVariable String worldSlug, + @RequestParam String tenantSlug) { String bootstrapToken = extractBearerToken(authorization); return ResponseEntity.ok( - ApiResponse.success(accountService.listBootstrapRealms(bootstrapToken, worldSlug))); + ApiResponse.success( + accountService.listBootstrapRealms(bootstrapToken, tenantSlug, worldSlug))); } @GetMapping("/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java index 9806a2487e..8e3bf534ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java @@ -1,4 +1,4 @@ package net.firedevops.firemud.accountservice.dto; -/** World visible to a bootstrap-authenticated first-party client. */ -public record BootstrapWorldDto(String worldSlug, String displayName) {} +/** Tenant-qualified world selector visible to a bootstrap-authenticated first-party client. */ +public record BootstrapWorldDto(String tenantSlug, String worldSlug, String displayName) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java index 5c8cfbe185..ecf214efd4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java @@ -67,7 +67,6 @@ public List listWorlds(String bootstrapToken) { new IllegalStateException("Canonical public target collection changed during discovery")); } - rejectAmbiguousWorldSlugs(initialTargets); requireSameCaller(originalCaller, verifyCaller(bootstrapToken)); requireFreshEvaluations(initialByTenant, evaluated); @@ -76,10 +75,14 @@ public List listWorlds(String bootstrapToken) { AccountPublicBootstrapEntitlementOwner.Evaluation evaluation = evaluated.get(target.canonicalTenantId()); if (evaluation.gameplayAvailable()) { - visible.add(new BootstrapWorldDto(target.worldSlug(), target.worldDisplayName())); + visible.add( + new BootstrapWorldDto( + target.tenantSlug(), target.worldSlug(), target.worldDisplayName())); } } - visible.sort(Comparator.comparing(BootstrapWorldDto::worldSlug)); + visible.sort( + Comparator.comparing(BootstrapWorldDto::worldSlug) + .thenComparing(BootstrapWorldDto::tenantSlug)); return List.copyOf(visible); } @@ -174,18 +177,6 @@ private Map targetsByCanonicalTenant(List completeTargets) return Map.copyOf(byTenant); } - private void rejectAmbiguousWorldSlugs(List completeTargets) { - Map tenantsByWorldSlug = new HashMap<>(); - for (Target target : completeTargets) { - UUID previousTenant = - tenantsByWorldSlug.putIfAbsent(target.worldSlug(), target.canonicalTenantId()); - if (previousTenant != null && !previousTenant.equals(target.canonicalTenantId())) { - throw admissionPointerUnavailable( - new IllegalStateException("Public world slug is ambiguous across canonical tenants")); - } - } - } - private void requireSameCaller(VerifiedCaller original, VerifiedCaller current) { if (original.accountId() != current.accountId() || !original.accountUuid().equals(current.accountUuid())) { 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 13795c7d9e..93c117a14c 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 @@ -46,7 +46,8 @@ net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmailLoginO java.util.List listBootstrapWorlds(String bootstrapToken); - java.util.List listBootstrapRealms(String bootstrapToken, String worldSlug); + java.util.List listBootstrapRealms( + String bootstrapToken, String tenantSlug, String worldSlug); java.util.List listBootstrapCharacters( String bootstrapToken, String worldSlug, String realmSlug, String connectScopeId); 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 4d12dab344..b2a918fe24 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 @@ -910,7 +910,8 @@ private void requireSameBootstrapCaller(BootstrapContext original, String token) @Override @Timed(value = "account.bootstrap_realms") - public List listBootstrapRealms(String bootstrapToken, String worldSlug) { + public List listBootstrapRealms( + String bootstrapToken, String tenantSlug, String worldSlug) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException("Public bootstrap realm discovery refuses ambient SQL"); @@ -920,7 +921,7 @@ public List listBootstrapRealms(String bootstrapToken, String throw new AuthenticationException( "AUTH_UNAVAILABLE", "Canonical public-realm scope source is unavailable"); } - return owner.listRealmScopes(bootstrapToken, worldSlug).stream() + return owner.listRealmScopes(bootstrapToken, tenantSlug, worldSlug).stream() .map( retained -> { var target = retained.target(); diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 198a024c09..09cc4c7e7e 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -182,7 +182,11 @@ components: type: boolean BootstrapWorldDto: type: object + description: Tenant-qualified world selector; worldSlug is not globally unique. + required: [tenantSlug, worldSlug, displayName] properties: + tenantSlug: + type: string worldSlug: type: string displayName: @@ -436,7 +440,7 @@ paths: $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/bootstrap/worlds/{worldSlug}/realms: get: - summary: List caller-visible realms for a selected world + summary: List caller-visible realms for a tenant-qualified world operationId: listBootstrapRealms security: - bearerAuth: [] @@ -446,6 +450,12 @@ paths: required: true schema: type: string + - in: query + name: tenantSlug + required: true + description: Tenant selector from the selected BootstrapWorldDto; required because worldSlug is tenant-scoped. + schema: + type: string responses: '200': description: Visible realms 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 21460ae893..1b70552618 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 @@ -1799,7 +1799,10 @@ private Target target() { } private String browserScope() { - return service.listBootstrapRealms(bootstrap, target.worldSlug()).getFirst().connectScopeId(); + return service + .listBootstrapRealms(bootstrap, target.tenantSlug(), target.worldSlug()) + .getFirst() + .connectScopeId(); } private List characters( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 8334d3b361..15b72d484c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -644,7 +644,8 @@ private String discoverConnectScope(TestAccount account, String token) throws Ex accountBaseUrl() + "/auth/bootstrap/worlds/" + SOURCE.target().worldSlug() - + "/realms")) + + "/realms?tenantSlug=" + + accountTarget().tenantSlug())) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); @@ -653,7 +654,9 @@ private String discoverConnectScope(TestAccount account, String token) throws Ex // Preserve the HTTP assertion while exposing an owner/proxy exception otherwise hidden by // the public INTERNAL_ERROR projection. This uses the same actual caller and owner setup. org.assertj.core.api.Assertions.assertThatCode( - () -> facade.listBootstrapRealms(token, SOURCE.target().worldSlug())) + () -> + facade.listBootstrapRealms( + token, accountTarget().tenantSlug(), SOURCE.target().worldSlug())) .as("REALMS owner composition after HTTP response: %s", response.body()) .doesNotThrowAnyException(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java index c17b6a2360..7bf0e1e2d5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -150,12 +150,12 @@ void actualDemoHeadsProduceSortedPublicWorldsWithoutMembershipJoinOrAnyReadMutat assertThat(f.worlds.listWorlds(f.token)) .containsExactly( - new BootstrapWorldDto("alpha", "World alpha"), - new BootstrapWorldDto("zulu", "World zulu")); + new BootstrapWorldDto(alpha.target().tenantSlug(), "alpha", "World alpha"), + new BootstrapWorldDto(zulu.target().tenantSlug(), "zulu", "World zulu")); assertThat(f.worlds.listWorlds(f.token)) .containsExactly( - new BootstrapWorldDto("alpha", "World alpha"), - new BootstrapWorldDto("zulu", "World zulu")); + new BootstrapWorldDto(alpha.target().tenantSlug(), "alpha", "World alpha"), + new BootstrapWorldDto(zulu.target().tenantSlug(), "zulu", "World zulu")); assertThat(f.snapshot()).isEqualTo(before); assertThat(f.inTransaction(() -> f.sources.readCurrentSourceSelection(alpha.tenantId()).kind())) 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 1d9ab6e91e..d5cd84e263 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 @@ -262,18 +262,19 @@ void connectTokenSetsCookieAndReturnsMetadataOnly() throws Exception { @Test void listBootstrapWorldsReturnsVisibleWorlds() throws Exception { when(accountService.listBootstrapWorlds("boot123")) - .thenReturn(List.of(new BootstrapWorldDto("demo", "Demo World"))); + .thenReturn(List.of(new BootstrapWorldDto("tenant-demo", "demo", "Demo World"))); mockMvc .perform(get("/auth/bootstrap/worlds").header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data[0].tenantSlug").value("tenant-demo")) .andExpect(jsonPath("$.data[0].worldSlug").value("demo")); } @Test void listBootstrapRealmsReturnsVisibleRealms() throws Exception { - when(accountService.listBootstrapRealms("boot123", "demo")) + when(accountService.listBootstrapRealms("boot123", "tenant-demo", "demo")) .thenReturn( List.of( new BootstrapRealmDto( @@ -296,6 +297,7 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { mockMvc .perform( get("/auth/bootstrap/worlds/demo/realms") + .param("tenantSlug", "tenant-demo") .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) @@ -314,6 +316,16 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(jsonPath("$.data[0].connectScopeId").value("scope-1")); } + @Test + void listBootstrapRealmsRequiresTenantSelector() throws Exception { + mockMvc + .perform( + get("/auth/bootstrap/worlds/demo/realms") + .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) + .andExpect(status().isBadRequest()); + org.mockito.Mockito.verifyNoInteractions(accountService); + } + @Test void listBootstrapCharactersReturnsCharacters() throws Exception { when(accountService.listBootstrapCharacters("boot123", "demo", "production", "scope-1")) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java index fc6bdb624c..e718012026 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java @@ -81,7 +81,8 @@ void returnsSortedPublicWorldsAfterCompleteStableReorderedSourceAndFinalCallerCh assertThat(worlds) .containsExactly( - new BootstrapWorldDto("alpha", "Alpha"), new BootstrapWorldDto("zulu", "Zulu")); + new BootstrapWorldDto("tenant-b", "alpha", "Alpha"), + new BootstrapWorldDto("tenant-a", "zulu", "Zulu")); verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); verify(f.entitlements).evaluate(TENANT_A); verify(f.entitlements).evaluate(TENANT_B); @@ -101,7 +102,8 @@ void mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery() { .thenReturn(evaluation(TENANT_B, true, NOW.plusSeconds(30))); assertThat(f.owner.listWorlds(TOKEN)) .containsExactly( - new BootstrapWorldDto("created", "Created"), new BootstrapWorldDto("seeded", "Seeded")); + new BootstrapWorldDto("tenant-b", "created", "Created"), + new BootstrapWorldDto("tenant-a", "seeded", "Seeded")); verify(f.entitlements, times(1)).evaluate(TENANT_A); verify(f.entitlements, times(1)).evaluate(TENANT_B); } @@ -138,7 +140,7 @@ void changedCompleteTargetRefusesTheWholeList() { } @Test - void ambiguousWorldSlugAcrossTenantsRefusesWithoutReturningEitherWorld() { + void sharedWorldSlugAcrossTenantsReturnsBothQualifiedSelectors() { Fixture f = new Fixture(); Target first = target(TENANT_A, "tenant-a", "same-slug", "First", 1); Target second = target(TENANT_B, "tenant-b", "same-slug", "Second", 1); @@ -148,7 +150,10 @@ void ambiguousWorldSlugAcrossTenantsRefusesWithoutReturningEitherWorld() { when(f.entitlements.evaluate(TENANT_B)) .thenReturn(evaluation(TENANT_B, true, NOW.plusSeconds(30))); - assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + assertThat(f.owner.listWorlds(TOKEN)) + .containsExactly( + new BootstrapWorldDto("tenant-a", "same-slug", "First"), + new BootstrapWorldDto("tenant-b", "same-slug", "Second")); } @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 ce60a70c84..1f09c577a8 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 @@ -234,11 +234,13 @@ void bootstrapRealmsDelegatesWorldAndCredentialAndProjectsRetainedUuidScopeWitho RealmScope retained = org.mockito.Mockito.mock(RealmScope.class); when(retained.target()).thenReturn(target); when(retained.scope()).thenReturn(scope); - when(owner.listRealmScopes("canonical-bootstrap", "demo")).thenReturn(List.of(retained)); + when(owner.listRealmScopes("canonical-bootstrap", "source-tenant", "demo")) + .thenReturn(List.of(retained)); org.mockito.Mockito.clearInvocations( accountRepository, sessionService, jwtUtil, retainedSubscriptionEvidenceRepository); - var result = service.listBootstrapRealms("canonical-bootstrap", "demo").getFirst(); + var result = + service.listBootstrapRealms("canonical-bootstrap", "source-tenant", "demo").getFirst(); assertEquals(scope.worldSlug(), result.worldSlug()); assertEquals(scope.realmSlug(), result.realmSlug()); @@ -256,7 +258,8 @@ void bootstrapRealmsDelegatesWorldAndCredentialAndProjectsRetainedUuidScopeWitho assertEquals(scope.connectScopeExpiresAt(), result.connectScopeExpiresAt()); assertEquals(scope.connectScopeId(), result.connectScopeId()); assertFalse(result.toString().contains(scope.connectScopeId())); - org.mockito.Mockito.verify(owner).listRealmScopes("canonical-bootstrap", "demo"); + org.mockito.Mockito.verify(owner) + .listRealmScopes("canonical-bootstrap", "source-tenant", "demo"); verifyNoInteractions( accountRepository, sessionService, jwtUtil, retainedSubscriptionEvidenceRepository); } @@ -267,7 +270,8 @@ void bootstrapRealmsWithoutCanonicalCompositionRefusesBeforeAccountOrSessionWork AuthenticationException failure = assertThrows( - AuthenticationException.class, () -> service.listBootstrapRealms("bootstrap", "demo")); + AuthenticationException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo")); assertEquals("AUTH_UNAVAILABLE", failure.getCode()); verifyNoInteractions(accountRepository, sessionService); @@ -286,13 +290,14 @@ void bootstrapRealmsPreservesCanonicalSourceRefusal(String code) { org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); service.setCanonicalPublicRealmScopeOwner(owner); AuthenticationException failure = new AuthenticationException(code, "Canonical source refusal"); - when(owner.listRealmScopes("bootstrap", "demo")).thenThrow(failure); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")).thenThrow(failure); org.mockito.Mockito.clearInvocations(accountRepository, sessionService); assertSame( failure, assertThrows( - AuthenticationException.class, () -> service.listBootstrapRealms("bootstrap", "demo"))); + AuthenticationException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo"))); verifyNoInteractions(accountRepository, sessionService); } @@ -307,7 +312,8 @@ void bootstrapRealmsRefusesAmbientSqlBeforeCanonicalSource(boolean synchronizati else TransactionSynchronizationManager.setActualTransactionActive(true); try { assertThrows( - IllegalStateException.class, () -> service.listBootstrapRealms("bootstrap", "demo")); + IllegalStateException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo")); verifyNoInteractions(owner); } finally { TransactionSynchronizationManager.clear(); @@ -320,7 +326,7 @@ void bootstrapRealmsKeepsPlayerContextForTheComposedOwnersWorkloadGuard() { org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); service.setCanonicalPublicRealmScopeOwner(owner); SessionContext.setContext("e9e3aa54-9712-4e01-8767-f23f3c662e64", List.of(), Map.of()); - when(owner.listRealmScopes("bootstrap", "demo")) + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")) .thenAnswer( invocation -> { assertTrue(SessionContext.hasAuthenticatedCallerContext()); @@ -328,7 +334,8 @@ void bootstrapRealmsKeepsPlayerContextForTheComposedOwnersWorkloadGuard() { }); try { assertThrows( - IllegalStateException.class, () -> service.listBootstrapRealms("bootstrap", "demo")); + IllegalStateException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo")); assertTrue(SessionContext.hasAuthenticatedCallerContext()); } finally { SessionContext.clear(); @@ -341,7 +348,9 @@ void bootstrapWorldsDelegatesExactCredentialAndCompleteResultToCanonicalOwner() org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); service.setPublicBootstrapWorldsOwner(owner); List worlds = - List.of(new BootstrapWorldDto("alpha", "Alpha"), new BootstrapWorldDto("zulu", "Zulu")); + List.of( + new BootstrapWorldDto("tenant-alpha", "alpha", "Alpha"), + new BootstrapWorldDto("tenant-zulu", "zulu", "Zulu")); when(owner.listWorlds("canonical-bootstrap")).thenReturn(worlds); org.mockito.Mockito.clearInvocations(accountRepository, sessionService); @@ -3165,11 +3174,12 @@ void bootstrapRealmFacadePreservesCanonicalTargetAndPolicyRefusal(String code) { var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); service.setCanonicalPublicRealmScopeOwner(owner); var refusal = new AuthenticationException(code, "controlled current canonical source refusal"); - when(owner.listRealmScopes("bootstrap", "demo")).thenThrow(refusal); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")).thenThrow(refusal); assertSame( refusal, assertThrows( - AuthenticationException.class, () -> service.listBootstrapRealms("bootstrap", "demo"))); + AuthenticationException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo"))); verifyNoInteractions(accountTenantMembershipRepository, accountRealmAccessGrantRepository); } @@ -3178,7 +3188,8 @@ void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceLeaveTransactionsToCanonic throws Exception { for (var method : List.of( - AccountServiceImpl.class.getMethod("listBootstrapRealms", String.class, String.class), + AccountServiceImpl.class.getMethod( + "listBootstrapRealms", String.class, String.class, String.class), AccountServiceImpl.class.getMethod( "issueDirectTextConnectScope", DirectTextCallerContext.class, @@ -3625,8 +3636,8 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerCanonicalTenantPerInvocatio var expectedWorlds = List.of( - new BootstrapWorldDto("demo", "Demo World"), - new BootstrapWorldDto("sandbox", "Sandbox World")); + new BootstrapWorldDto("tenant-demo", "demo", "Demo World"), + new BootstrapWorldDto("tenant-sandbox", "sandbox", "Sandbox World")); assertEquals(expectedWorlds, firstCall); assertEquals(expectedWorlds, secondCall); org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) @@ -3698,8 +3709,8 @@ void listBootstrapWorldsFiltersGameplayUnavailableTenantAndFailsWhenEntitlementI void bootstrapPublicRealmFacadePreservesEmptyCanonicalOwnerResult() { var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); service.setCanonicalPublicRealmScopeOwner(owner); - when(owner.listRealmScopes("bootstrap", "demo")).thenReturn(List.of()); - assertTrue(service.listBootstrapRealms("bootstrap", "demo").isEmpty()); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")).thenReturn(List.of()); + assertTrue(service.listBootstrapRealms("bootstrap", "source-tenant", "demo").isEmpty()); verifyNoInteractions(accountRealmAccessGrantRepository, accountTenantMembershipRepository); } @@ -4798,6 +4809,7 @@ private CanonicalWorldDiscoveryFixture composeCanonicalWorldDiscovery(List Date: Mon, 9 Nov 2026 12:52:20 +1300 Subject: [PATCH 55/66] Preserve committed JOIN replay outcomes --- .../service/impl/AccountServiceImpl.java | 14 +++---- .../service/impl/AccountServiceImplTest.java | 40 +++++++++++++++++-- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index b2a918fe24..40d780cbef 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 @@ -681,17 +681,15 @@ private CanonicalJoinResult commitCanonicalJoin( scope.accountId(), scope.tenantId()); boolean active = member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); - if (!gameplayAvailable || (!active && !allowPublicJoin)) { + if ("PENDING".equals(policyBoundOperation.status()) + && (!gameplayAvailable || (!active && !allowPublicJoin))) { String outcome = gameplayAvailable ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" : "TENANT_BILLING_BLOCKED"; - if ("PENDING".equals(policyBoundOperation.status())) { - accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, outcome); - } - return new CanonicalJoinResult( - outcome, null, false, !"PENDING".equals(policyBoundOperation.status())); + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, outcome); + return new CanonicalJoinResult(outcome, null, false, false); } var committed = consumers @@ -709,7 +707,7 @@ private CanonicalJoinResult commitCanonicalJoin( scope.accountId(), scope.tenantId()); if ("COMMITTED".equals(policyBoundOperation.status())) { // A committed exact retry returns its original operation proof after the current - // policy check above. Membership may have changed since that proof was retained; + // policy binding above. Membership may have changed since that proof was retained; // expose only the current admission flag, never use the old proof as admission. return new CanonicalJoinResult( committed.outcome(), 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 1f09c577a8..d64b564216 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 @@ -916,14 +916,48 @@ void canonicalConcurrentCommitUsesLockedReplayStateAndStillChecksCurrentPolicy(b var result = f.browserJoin(); assertTrue(result.replayed()); - assertEquals(gameplay, result.success()); - assertEquals(gameplay ? "JOINED" : "TENANT_BILLING_BLOCKED", result.outcomeCode()); + assertTrue(result.success()); + assertEquals("JOINED", result.outcomeCode()); org.mockito.Mockito.verify(f.demos).revalidate(f.demo); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) .finishCanonicalFailure( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); - if (!gameplay) verifyNoInteractions(f.terminal); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } + + @Test + void canonicalCommittedAlreadyActiveRetryPreservesReceiptAfterMembershipBecomesInactive() { + var f = canonicalJoinFixture(); + f.terminal("ALREADY_ACTIVE", 7L, 3L); + when(f.pending.status()).thenReturn("COMMITTED"); + when(f.demo.allowPublicJoin()).thenReturn(false); + f.currentMembership.setLifecycleState("INACTIVE"); + f.currentMembership.setGameplayAdmissionAllowed(false); + f.currentMembership.setMembershipVersion(8L); + f.currentMembership.setMembershipAuthorityGeneration(4L); + f.joined.set(true); + + var result = f.browserJoin(); + + assertTrue(result.success()); + assertTrue(result.replayed()); + assertEquals("ALREADY_ACTIVE", result.outcomeCode()); + assertEquals(7L, result.membershipVersion()); + assertEquals(3L, result.membershipAuthorityGeneration()); + assertFalse(result.gameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, f.binding, false, 1L); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + verifyNoInteractions(accountAuditOutboxRepository); } @Test From d89aad4e6cc2ee7851b94bb5a35097f00a807a6b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 13:48:20 +1300 Subject: [PATCH 56/66] Fix Hosted12 qualified selector contract and focused proof gaps --- .../account-service/api-contracts.md | 4 +- .../system-architecture-testing.md | 4 +- .../run-player-experience-smoke.py | 18 +++++ ...player-experience-smoke-runner-contract.sh | 80 +++++++++++++++++++ dev-tools/tests/smoke-transport-contract.sh | 25 +++++- ...AccountCanonicalPublicRealmScopeOwner.java | 5 -- .../AccountApplicationIntegrationTest.java | 15 +++- ...emoWorldsOwnerPostgresIntegrationTest.java | 18 ++++- ...untCanonicalPublicRealmScopeOwnerTest.java | 29 ++++--- 9 files changed, 171 insertions(+), 27 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3fff9c7097..522c02cb18 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -378,7 +378,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | Provider-specific callback route (future) | Not yet routable | Link one server-verified provider identity after that provider's complete contract and proof exist; the caller-asserted `/accounts/{accountId}/external` route is unsupported | | `POST` | `/auth/player-bootstrap` | Current endpoint; **target registry-backed behavior:** return a short-lived `player-bootstrap` token for gameplay bootstrap only after Account has atomically established exactly one active issued-token registry record; registry failure fails issuance before the token is exposed, and the token is not the `/auth/login` control-ui session | | `GET` | `/auth/bootstrap/worlds` | List caller-visible worlds for first-party gameplay bootstrap | -| `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | +| `GET` | `/auth/bootstrap/worlds/{world}/realms?tenantSlug={tenant}` | List caller-visible realms for a tenant-qualified world during first-party gameplay bootstrap; see [Public bootstrap WORLDS discovery](#public-bootstrap-worlds-discovery). | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. Account's local creation protection covers the current authenticated player's membership, applicable realm grant, and entitlement authority; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection) for the cross-owner terminal boundary. | | `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** A prepared Account `JoinPublicProductionMembership` component implements explicit public-production membership creation. See [Current Receiver Composition](#current-receiver-composition) for receiver availability. Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | @@ -442,7 +442,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/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | 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 ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. Default discovery remains unavailable; JOIN and connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. 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. Target success delivery uses only 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. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms?tenantSlug={tenant}`, `/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 ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. Default discovery remains unavailable; JOIN and connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. 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. Target success delivery uses only 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. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | 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. | diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 689e7ca94e..132d9687c2 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -145,7 +145,9 @@ This example is illustrative rather than exhaustive and shows the target-state a The `logPipelineQueryability` object above is the default indexed-profile form under [ADR 0162](./decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md) and the canonical [Log Pipeline Queryability Contract](./system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). Its closed capability vocabulary is `indexed-log-observability`, `console-journal-log-observability`, or `log-queryability-omitted`; non-omitted evidence uses `result="passed"` or `result="failed"`, while `result="not_applicable"` is reserved for explicit omission. `backend` and `storageTarget` identify where a non-omitted record is retained; `queryPath` identifies the final supported operator surface and must not contain only an index or stream convention. A `passed` result is valid only when the fresh unique `recordId` and known `traceId` identify the exact retrieved record, `verifiedFields` records every asserted source field, the timestamps are chronological (`emittedAt <= retrievedAt <= evidenceObservedAt <= verifiedAt`), `observedDelaySeconds` equals `retrievedAt - emittedAt`, the observed delay is no greater than `configuredDelayTargetSeconds`, and the retained evidence has not passed `evidenceExpiresAt`. Every result carries a positive finite, profile-resolved `evidenceFreshnessBudgetSeconds`; `evidenceExpiresAt` must equal `evidenceObservedAt + evidenceFreshnessBudgetSeconds`. `verifiedAt` is the trusted evaluator completion time, so source timestamps cannot be future-dated relative to it. A compatible indexed backend retains the same fields with its mapped storage target and supported query path. A reduced profile that advertises console or journal retrieval proves the same unique-record retrieval and timing through its declared backend, storage target, and final operator query path. A failed result is non-authorizing in readiness validation and is accepted only with the explicit incident/failure-evidence mode. A profile that explicitly omits queryability records the selected profile, `capability="log-queryability-omitted"`, `result="not_applicable"`, its omission reason, observation/expiry timestamps, and an evidence reference without fabricating indexed or retrieval fields such as backend, storage target, query path, emission/retrieval timestamps, delay measurements, record identity, source identity, or verified fields. -Use `python3 dev-tools/observability/run-player-experience-smoke.py --external-authority-evidence --queryability-profile --queryability-freshness-budget-seconds --evidence-out [--metrics-out ] [--synthetic-identity-evidence ]` to generate the journey and mirrored-signal part of hosted-assurance smoke evidence, incorporate actual results from the separately exercised canary alert path, then run `python3 dev-tools/observability/validate-player-experience-smoke-evidence.py ` before attaching the completed result to a traffic-open or recovery record. `authority.json` must be the retained profile-aware result from the authoritative external monitor for the deadman and declared public paths, or an explicit `independent-omitted` record with its degraded-detection reason. An advertised player-flow canary additionally requires an implemented authoritative synthetic identity/isolation verifier; until that verifier exists, the runner downgrades the request to `playerFlowCanary=omitted` even when a local `identity.json` contains plausible assertions, and the validator rejects retained evidence that claims `advertised`. The queryability profile and positive freshness budget must be supplied by the selected deployment profile and must match the target environment's expected-bindings declaration; the runner does not invent defaults. The validator uses current UTC by default, or a trusted `--evaluation-time ` seam for deterministic contract tests. Only `--simulate` may synthesize that authority object. +For a live run that exposes WebSocket with published Prometheus mirrors, set `PLAYER_EXPERIENCE_WORLD=` and `PLAYER_EXPERIENCE_TENANT_SLUG=` to the matching world/tenant pair from the Account bootstrap-world listing; world slugs are not globally unique. An authorized player-flow canary on an exposed WebSocket path requires the same selector. The runner checks this configuration before readiness, account, authentication, or WebSocket requests. Simulation, omitted mirrors with no authorized canary, and profiles that expose no WebSocket path do not require the selector. + +Use `PLAYER_EXPERIENCE_WORLD= PLAYER_EXPERIENCE_TENANT_SLUG= python3 dev-tools/observability/run-player-experience-smoke.py --external-authority-evidence --queryability-profile --queryability-freshness-budget-seconds --evidence-out [--metrics-out ] [--synthetic-identity-evidence ]` to generate the journey and mirrored-signal part of hosted-assurance smoke evidence, incorporate actual results from the separately exercised canary alert path, then run `python3 dev-tools/observability/validate-player-experience-smoke-evidence.py ` before attaching the completed result to a traffic-open or recovery record. `authority.json` must be the retained profile-aware result from the authoritative external monitor for the deadman and declared public paths, or an explicit `independent-omitted` record with its degraded-detection reason. An advertised player-flow canary additionally requires an implemented authoritative synthetic identity/isolation verifier; until that verifier exists, the runner downgrades the request to `playerFlowCanary=omitted` even when a local `identity.json` contains plausible assertions, and the validator rejects retained evidence that claims `advertised`. The queryability profile and positive freshness budget must be supplied by the selected deployment profile and must match the target environment's expected-bindings declaration; the runner does not invent defaults. The validator uses current UTC by default, or a trusted `--evaluation-time ` seam for deterministic contract tests. Only `--simulate` may synthesize that authority object. The default runner intake and validator invocation are readiness-strict: every exposed path and advertised canary flow must be green, and every required alert family must have an actually exercised `passed` result, so promotion and recovery consumers fail closed on a current failure or an unproved alert path. For incident capture and alert-path diagnosis only, pass `--allow-failure-evidence` to the runner when the retained source authority is red and to the validator when checking the resulting artifact. That mode accepts structurally complete current red deadman/public-path authority, zero-valued failed or prerequisite-blocked path/canary records, and `failed` or `not_exercised` alert-path results. It keeps external-authority shape, provenance, chronology, freshness, and record completeness strict and must not be used as traffic-open or recovery authority. diff --git a/dev-tools/observability/run-player-experience-smoke.py b/dev-tools/observability/run-player-experience-smoke.py index f2924bd3bb..c7c68a05f4 100644 --- a/dev-tools/observability/run-player-experience-smoke.py +++ b/dev-tools/observability/run-player-experience-smoke.py @@ -302,6 +302,14 @@ def main() -> int: allow_unadvertised_canary_budget=requested_canary_advertised, ) establish_player_flow_canary_capability(config, initial_external_authority) + try: + validate_live_websocket_tenant_selector( + config, + declared_exposed_paths(initial_external_authority), + simulate=args.simulate, + ) + except ProbeOperationalFailure as exc: + parser.error(str(exc)) try: validate_telnet_transport_config( config, @@ -2079,6 +2087,16 @@ def require_tenant_selector(config: SmokeConfig) -> None: ) +def validate_live_websocket_tenant_selector( + config: SmokeConfig, exposed_paths: set[str], *, simulate: bool +) -> None: + """Preflight tenant selection when a live WebSocket smoke will execute.""" + if simulate or "websocket" not in exposed_paths: + return + if config.prometheus_mirrors == "published" or canary_producer_is_authorized(config): + require_tenant_selector(config) + + def require_visible_world(config: SmokeConfig, bootstrap_token: str) -> None: require_tenant_selector(config) response = http_request_json( diff --git a/dev-tools/tests/player-experience-smoke-runner-contract.sh b/dev-tools/tests/player-experience-smoke-runner-contract.sh index f85d6fe308..135b905c2a 100644 --- a/dev-tools/tests/player-experience-smoke-runner-contract.sh +++ b/dev-tools/tests/player-experience-smoke-runner-contract.sh @@ -50,6 +50,7 @@ env "${SMOKE_CONFIG_ENV_UNSETS[@]}" \ PLAYER_EXPERIENCE_QUERYABILITY_FRESHNESS_BUDGET_SECONDS=7200 \ python3 - "$ROOT_DIR" <<'PY' import importlib.util +import io import sys from pathlib import Path from unittest.mock import patch @@ -83,6 +84,85 @@ assert env_config.telnet_transport is None assert env_config.telnet_server_hostname is None assert env_config.telnet_ca_file is None +# A live WebSocket mirror or authorized canary must have tenant scope before +# readiness, account, bootstrap, or transport requests begin. +try: + runner_module.validate_live_websocket_tenant_selector( + env_config, {"websocket"}, simulate=False + ) +except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) +else: + raise AssertionError("live WebSocket evidence accepted a missing tenant selector") +runner_module.validate_live_websocket_tenant_selector( + env_config, {"websocket"}, simulate=True +) +runner_module.validate_live_websocket_tenant_selector( + env_config, {"telnet"}, simulate=False +) +omitted_websocket = runner_module.SmokeConfig.from_env( + "contract-test", "websocket", None, prometheus_mirrors="omitted", + player_flow_canary="omitted", +) +runner_module.validate_live_websocket_tenant_selector( + omitted_websocket, {"websocket"}, simulate=False +) +authorized_canary = runner_module.SmokeConfig.from_env( + "contract-test", "websocket", None, prometheus_mirrors="omitted", + player_flow_canary="advertised", +) +authorized_canary.username = "non-default@example.com" +authorized_canary.password = "non-default-password" +authorized_canary.player_flow_canary_identity = { + "authority": "account-service", + "classification": "synthetic", + "analyticsSloExclusion": True, + "credentials": {"nonDefault": True, "productionSafe": True}, + "transportCharacters": { + "websocket": {"restricted": True, "isolated": True} + }, + "evidenceRef": "account://contract-test/synthetic-canary", +} +authorized_canary._validated_player_flow_canary_paths = frozenset({"websocket"}) +with patch.object(runner_module, "AUTHORITATIVE_CANARY_IDENTITY_VERIFIER_AVAILABLE", True): + try: + runner_module.validate_live_websocket_tenant_selector( + authorized_canary, {"websocket"}, simulate=False + ) + except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) + else: + raise AssertionError("authorized live WebSocket canary accepted missing tenant selector") + +# The CLI fails during configuration preflight, before any live readiness or +# account/auth request can be attempted. +with patch.object(runner_module.sys, "argv", [ + str(root / "run-player-experience-smoke.py"), + "--external-authority-evidence", "/tmp/contract-authority.json", + "--player-flow-canary", "omitted", + "--evidence-out", "/tmp/contract-evidence.json", +]): + with patch.object( + runner_module, "resolve_external_authority", + return_value={"profile": "independent-omitted", "exposedPublicPlayerPaths": ["websocket"]}, + ), patch.object(runner_module, "wait_for_account_schema") as wait_schema, patch.object( + runner_module, "wait_for_http_readiness" + ) as wait_http, patch.object(runner_module, "verify_smoke_account") as verify_account, patch.object( + runner_module, "http_request_json" + ) as auth_request, patch.object(runner_module, "execute_smoke") as execute: + try: + with patch("sys.stderr", new_callable=io.StringIO): + runner_module.main() + except SystemExit as exc: + assert exc.code == 2 + else: + raise AssertionError("live CLI did not reject a missing WebSocket tenant selector") + wait_schema.assert_not_called() + wait_http.assert_not_called() + verify_account.assert_not_called() + auth_request.assert_not_called() + execute.assert_not_called() + # Browser world selection remains qualified even when another tenant reuses its slug. assert env_config.tenant_slug is None with patch.object(runner_module, "http_request_json") as request: diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index e6e5a30bed..14dea193c2 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -70,7 +70,6 @@ for label, command, response, prior, expected_type in [ ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.PlayEntitlementUnavailable), ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE extra", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. more", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), - ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.\n", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Another message.", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), ("PLAY", "PLAY demo", "ERROR UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), ("PLAY", "LOOK demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), @@ -471,6 +470,30 @@ class CommandResponseSession(FakeSession): self.chunks = list(response) if isinstance(response, list) else [response] +# Exercise the newline-bearing server response through the real WebSocket +# reader. The reader strips the line ending before command-local classification. +newline_entitlement_session = CommandResponseSession([ + "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.\n" +]) +try: + smoke_common.send_websocket_command_and_expect( + newline_entitlement_session, + [], + "PLAY demo", + ["OK PLAY"], + "PLAY", + 1, + step_results=[{"label": "LOGIN", "response": "OK LOGIN account=demo"}], + ) +except smoke_common.PlayEntitlementUnavailable as exc: + assert str(exc) == ( + "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly." + ) +else: + raise AssertionError("newline entitlement failure did not retain its typed classification") +assert newline_entitlement_session.sent == ["PLAY demo"] + + class FakeTlsContext: def __init__(self, wrapped=None, failure=None): self.wrapped = wrapped or FakeSession() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index bec8508228..70a1aaf7fd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -117,11 +117,6 @@ public AccountCanonicalPublicRealmScopeOwner( transaction.setReadOnly(false); } - /** Resolves a world only when the complete public collection identifies one exact target. */ - public List listRealmScopes(String bootstrapToken, String worldSlug) { - return listRealmScopes(bootstrapToken, null, worldSlug, false); - } - /** Selects the canonical tenant/world pair through the same complete-source pipeline. */ public List listRealmScopes( String bootstrapToken, String tenantSlug, String worldSlug) { 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 1b70552618..ed7fc5ed23 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 @@ -879,9 +879,11 @@ void publicJoinChangedAvailablePolicyCannotRebindTheOriginalTerminalReceipt() { f.assertTransitionCount(1L); } - @Test - void publicJoinRestoresControlledInactiveSnapshotOnceAndPreservesAuthorityGeneration() { - var f = publicJoinFixture(false); + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinRestoresControlledInactiveSnapshotOnceAndPreservesAuthorityGeneration( + boolean paid) { + var f = publicJoinFixture(paid); String token = f.browserScope(); assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); f.seedControlledInactiveSnapshot(); @@ -902,6 +904,13 @@ void publicJoinRestoresControlledInactiveSnapshotOnceAndPreservesAuthorityGenera "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", f.tenantId)) .isEqualTo(2L); + var restoredEvent = f.in(() -> f.outbox.findEvent(f.stream(), 3L).orElseThrow()); + var decodedRestoredEvent = + MembershipAuthorityEventV1Codec.verify( + new String(restoredEvent.payload(), StandardCharsets.UTF_8)); + assertThat(decodedRestoredEvent.requestId()).isEqualTo(request); + assertThat(decodedRestoredEvent.outboxSequence()).isEqualTo("3"); + assertThat(decodedRestoredEvent.callerBoundAuthorityInvalidated()).isFalse(); var committed = f.state(request); assertThat(f.join(token, request).replayed()).isTrue(); assertThat(f.state(request)).isEqualTo(committed); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java index 7bf0e1e2d5..9654b5bc97 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -223,7 +224,7 @@ void originalDemoObservationExpiresDuringFinalCollectionReadWithoutRestamping() } @Test - void ambiguousWorldSlugAcrossTwoRealDemoTenantsRefusesInsteadOfChoosingOne() { + void repeatedWorldSlugAcrossTwoRealDemoTenantsReturnsBothQualifiedSelectorsInOrder() { Fixture f = fixture(); DemoTenant first = f.demo("same-world", true); DemoTenant second = f.demo("same-world", true); @@ -231,7 +232,20 @@ void ambiguousWorldSlugAcrossTwoRealDemoTenantsRefusesInsteadOfChoosingOne() { List.of(first.target(), second.target()), List.of(second.target(), first.target())); Map before = f.snapshot(); - assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + List expected = + List.of(first, second).stream() + .sorted( + Comparator.comparing((DemoTenant tenant) -> tenant.target().worldSlug()) + .thenComparing(tenant -> tenant.target().tenantSlug())) + .map( + tenant -> + new BootstrapWorldDto( + tenant.target().tenantSlug(), + tenant.target().worldSlug(), + tenant.target().worldDisplayName())) + .toList(); + + assertThat(f.worlds.listWorlds(f.token)).containsExactlyElementsOf(expected); assertThat(f.snapshot()).isEqualTo(before); f.assertNoAdmissionRowsOrPaidReads(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 9bb34691ce..9cd28712c3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -407,10 +407,10 @@ void exactTenantWorldSelectionNeverUsesABareGlobalWorldOrAnotherTenant() { } @Test - void globallyUniqueWorldUsesTheExactSourceTenantAndRetainedV2Scope() { + void qualifiedWorldUsesTheExactSourceTenantAndRetainedV2Scope() { Fixture f = new Fixture(300000L); - var result = f.owner.listRealmScopes(f.token, "world").getFirst(); + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); assertThat(result.target()).isEqualTo(f.target); assertThat(result.scope().tenantId()).isEqualTo(f.target.canonicalTenantId()); @@ -420,12 +420,13 @@ void globallyUniqueWorldUsesTheExactSourceTenantAndRetainedV2Scope() { } @Test - void globalWorldAmbiguityRefusesBeforeEntitlementOrAccountScopeSources() { + void qualifiedWorldAmbiguityWithinOneTenantRefusesBeforeEntitlementOrAccountScopeSources() { Fixture f = new Fixture(300000L); - Target other = target(UUID.randomUUID(), "another-tenant", 1L); - f.firstCollection = List.of(f.target, other); + Target duplicate = target(TENANT, "tenant", 1L); + f.firstCollection = List.of(f.target, duplicate); - assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "world")); + assertCode( + "ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); verifyNoInteractions(f.entitlements, f.tenants, f.heads, f.memberships, f.scopes); assertThat(f.transactions.started).isZero(); @@ -433,12 +434,13 @@ void globalWorldAmbiguityRefusesBeforeEntitlementOrAccountScopeSources() { @ParameterizedTest @ValueSource(booleans = {false, true}) - void globalWorldTenantReplacementOrNewAmbiguityOnRereadCannotPublishScope(boolean ambiguous) { + void qualifiedWorldReplacementOrAmbiguityOnRereadCannotPublishScope(boolean ambiguous) { Fixture f = new Fixture(300000L); - Target other = target(UUID.randomUUID(), "another-tenant", 1L); - f.secondCollection = ambiguous ? List.of(f.target, other) : List.of(other); + Target changed = target(TENANT, "tenant", 2L); + f.secondCollection = ambiguous ? List.of(f.target, changed) : List.of(changed); - assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "world")); + assertCode( + "ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); verifyNoInteractions(f.scopes); verify(f.entitlements).evaluate(TENANT); @@ -458,14 +460,15 @@ void qualifiedWorldSelectionUsesTheSamePipelineWithinTheCompleteCollection() { } @Test - void globalWorldAbsenceIsRereadWithoutMintingAndMalformedCallerPrecedesSelection() { + void qualifiedWorldAbsenceIsRereadWithoutMintingAndMalformedCallerPrecedesSelection() { Fixture f = new Fixture(300000L); f.firstCollection = List.of(); f.secondCollection = List.of(); - assertCode("CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes("malformed", "world")); + assertCode( + "CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes("malformed", "tenant", "world")); verifyNoInteractions(f.targets, f.entitlements, f.scopes); - assertThat(f.owner.listRealmScopes(f.token, "world")).isEmpty(); + assertThat(f.owner.listRealmScopes(f.token, "tenant", "world")).isEmpty(); assertThat(f.targetReads.get()).isEqualTo(2); verifyNoInteractions(f.entitlements, f.scopes, f.memberships); } From f4b4accbfc8dc56b81315dc61a3bdcd74ce99bc7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 14:14:14 +1300 Subject: [PATCH 57/66] Correct canonical JOIN attempt diagnostic availability --- .../service/impl/AccountServiceImpl.java | 4 +- .../service/impl/AccountServiceImplTest.java | 40 +++++++++++++++---- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 40d780cbef..d41891ebd7 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 @@ -1142,8 +1142,10 @@ private void recordCanonicalJoinFailure( .contains(failureCode) ? failureCode : "AUTH_UNAVAILABLE"; + String authorityAvailability = + "ENTITLEMENT_UNAVAILABLE".equals(retryCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; accountJoinOperationRepository.recordCanonicalAttemptFailure( - requestId, scope, callerBinding, "UNAVAILABLE", retryCode); + requestId, scope, callerBinding, authorityAvailability, retryCode); } }); } 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 d64b564216..767b0a0600 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 @@ -1207,7 +1207,7 @@ void canonicalJoinTargetFailureRetainsTheOriginalIntentWithoutAWrite(String code .finishCanonicalFailure(f.requestId, f.scope, f.binding, code); } else { org.mockito.Mockito.verify(accountJoinOperationRepository) - .recordCanonicalAttemptFailure(f.requestId, f.scope, f.binding, "UNAVAILABLE", code); + .recordCanonicalAttemptFailure(f.requestId, f.scope, f.binding, "NOT_EVALUATED", code); } verifyNoInteractions(f.terminal); } @@ -1320,7 +1320,7 @@ void canonicalJoinRemoteValidationFailureRemainsRetryable(String owner) { assertSame(failure, result.getCause()); org.mockito.Mockito.verify(accountJoinOperationRepository) .recordCanonicalAttemptFailure( - f.requestId, f.scope, f.binding, "UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"); + f.requestId, f.scope, f.binding, "NOT_EVALUATED", "ADMISSION_POINTER_UNAVAILABLE"); verifyNoInteractions(f.terminal); } @@ -1336,7 +1336,28 @@ void canonicalJoinStrictPublishedSourceOutageCannotUseResolverOnlyAuthority() { assertThrows(AuthenticationException.class, f::browserJoin).getCode()); org.mockito.Mockito.verify(accountJoinOperationRepository) .recordCanonicalAttemptFailure( - f.requestId, f.scope, f.binding, "UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"); + f.requestId, f.scope, f.binding, "NOT_EVALUATED", "ADMISSION_POINTER_UNAVAILABLE"); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinNonEntitlementFailureAfterPolicyBindingKeepsPolicySeparateFromAttempt() { + var f = canonicalJoinFixture(); + var failure = new AuthenticationException("AUTH_UNAVAILABLE", "controlled member outage"); + when(accountTenantMembershipRepository.findFreshMembershipForUpdate( + f.scope.accountId(), f.scope.tenantId())) + .thenThrow(failure); + + assertSame(failure, assertThrows(AuthenticationException.class, f::browserJoin)); + + var order = org.mockito.Mockito.inOrder(accountJoinOperationRepository); + order + .verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, f.binding, true, 1L); + order + .verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "NOT_EVALUATED", "AUTH_UNAVAILABLE"); verifyNoInteractions(f.terminal); } @@ -1425,9 +1446,13 @@ void canonicalJoinReturnsCommittedReceiptWhenScopeExpiresAfterCommit() { } @ParameterizedTest - @ValueSource( - strings = {"AUTH_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"}) - void canonicalJoinPreservesTypedFailureWhenRecordingFails(String code) { + @CsvSource({ + "AUTH_UNAVAILABLE,NOT_EVALUATED", + "ENTITLEMENT_UNAVAILABLE,UNAVAILABLE", + "ADMISSION_POINTER_UNAVAILABLE,NOT_EVALUATED" + }) + void canonicalJoinPreservesTypedFailureWhenRecordingFails( + String code, String authorityAvailability) { var f = canonicalJoinFixture(); var primary = new AuthenticationException(code, "controlled primary source failure"); var recording = @@ -1438,7 +1463,8 @@ void canonicalJoinPreservesTypedFailureWhenRecordingFails(String code) { .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); org.mockito.Mockito.doThrow(recording) .when(accountJoinOperationRepository) - .recordCanonicalAttemptFailure(f.requestId, f.scope, f.binding, "UNAVAILABLE", code); + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, authorityAvailability, code); var failure = assertThrows(AuthenticationException.class, f::browserJoin); From def89953195c975e9d88781793d8e3fd1311285e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 14:33:37 +1300 Subject: [PATCH 58/66] Fix smoke tenant intake and optional capture fallback --- .../run-player-experience-smoke.py | 5 ++- ...player-experience-smoke-runner-contract.sh | 34 +++++++++++++++++-- .../tests/test_gradle_compile_failure.py | 31 +++++++++++++++++ .../collect-gradle-compile-failure.py | 11 +++++- 4 files changed, 76 insertions(+), 5 deletions(-) diff --git a/dev-tools/observability/run-player-experience-smoke.py b/dev-tools/observability/run-player-experience-smoke.py index c7c68a05f4..aafe50030a 100644 --- a/dev-tools/observability/run-player-experience-smoke.py +++ b/dev-tools/observability/run-player-experience-smoke.py @@ -513,6 +513,9 @@ def from_env( ) if telnet_ca_file is None and os.environ.get("PLAYER_EXPERIENCE_TELNET_CA_FILE"): telnet_ca_file = Path(os.environ["PLAYER_EXPERIENCE_TELNET_CA_FILE"]) + tenant_slug = os.environ.get("PLAYER_EXPERIENCE_TENANT_SLUG") + if tenant_slug is not None: + tenant_slug = tenant_slug.strip() or None return cls( source=source, canary_path=canary_path, @@ -544,7 +547,7 @@ def from_env( username=os.environ.get("SMOKE_USERNAME", DEFAULT_SMOKE_USERNAME), password=os.environ.get("SMOKE_PASSWORD", DEFAULT_SMOKE_PASSWORD), world=os.environ.get("PLAYER_EXPERIENCE_WORLD", "demo"), - tenant_slug=os.environ.get("PLAYER_EXPERIENCE_TENANT_SLUG"), + tenant_slug=tenant_slug, timeout_seconds=int(os.environ.get("SMOKE_TIMEOUT_SECONDS", "10")), startup_wait_seconds=int(os.environ.get("SMOKE_STARTUP_WAIT_SECONDS", "90")), external_authority_evidence=external_authority_evidence, diff --git a/dev-tools/tests/player-experience-smoke-runner-contract.sh b/dev-tools/tests/player-experience-smoke-runner-contract.sh index 135b905c2a..e43903cace 100644 --- a/dev-tools/tests/player-experience-smoke-runner-contract.sh +++ b/dev-tools/tests/player-experience-smoke-runner-contract.sh @@ -140,6 +140,8 @@ with patch.object(runner_module.sys, "argv", [ str(root / "run-player-experience-smoke.py"), "--external-authority-evidence", "/tmp/contract-authority.json", "--player-flow-canary", "omitted", + "--queryability-profile", "staging", + "--queryability-freshness-budget-seconds", "7200", "--evidence-out", "/tmp/contract-evidence.json", ]): with patch.object( @@ -149,18 +151,25 @@ with patch.object(runner_module.sys, "argv", [ runner_module, "wait_for_http_readiness" ) as wait_http, patch.object(runner_module, "verify_smoke_account") as verify_account, patch.object( runner_module, "http_request_json" - ) as auth_request, patch.object(runner_module, "execute_smoke") as execute: + ) as auth_request, patch.object( + runner_module, "http_request_json_with_headers" + ) as auth_request_with_headers, patch.object( + runner_module, "execute_smoke" + ) as execute: + stderr = io.StringIO() try: - with patch("sys.stderr", new_callable=io.StringIO): + with patch("sys.stderr", stderr): runner_module.main() except SystemExit as exc: assert exc.code == 2 else: raise AssertionError("live CLI did not reject a missing WebSocket tenant selector") + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in stderr.getvalue() wait_schema.assert_not_called() wait_http.assert_not_called() verify_account.assert_not_called() auth_request.assert_not_called() + auth_request_with_headers.assert_not_called() execute.assert_not_called() # Browser world selection remains qualified even when another tenant reuses its slug. @@ -173,8 +182,14 @@ with patch.object(runner_module, "http_request_json") as request: else: raise AssertionError("Bare browser world selector was accepted") request.assert_not_called() -with patch.dict("os.environ", {"PLAYER_EXPERIENCE_TENANT_SLUG": "tenant-b"}): +with patch.dict("os.environ", {"PLAYER_EXPERIENCE_TENANT_SLUG": " tenant-b \t"}): qualified = runner_module.SmokeConfig.from_env("contract-test", "websocket", None) +assert qualified.tenant_slug == "tenant-b" +with patch.object(runner_module, "http_request_json", return_value={"data": [ + {"worldSlug": qualified.world, "tenantSlug": qualified.tenant_slug} +]}) as request: + runner_module.require_visible_world(qualified, "bootstrap") + request.assert_called_once() with patch.object(runner_module, "http_request_json", return_value={"data": [ {"worldSlug": qualified.world, "tenantSlug": "tenant-a"} ]}) as request: @@ -189,6 +204,19 @@ with patch.object(runner_module, "http_request_json", return_value={"data": [ ]}) as request: assert runner_module.resolve_connect_scope_id(qualified, "bootstrap") == "qualified-scope" assert request.call_args.args[0].endswith("/realms?tenantSlug=tenant-b") +with patch.dict("os.environ", {"PLAYER_EXPERIENCE_TENANT_SLUG": " \t "}): + whitespace_only = runner_module.SmokeConfig.from_env( + "contract-test", "websocket", None + ) +assert whitespace_only.tenant_slug is None +with patch.object(runner_module, "http_request_json") as request: + try: + runner_module.resolve_connect_scope_id(whitespace_only, "bootstrap") + except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) + else: + raise AssertionError("Whitespace-only tenant selector was accepted") + request.assert_not_called() runner_module.validate_telnet_transport_config( env_config, {"websocket"}, simulate=False diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 465e29fe61..1f67bfe12b 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -414,6 +414,37 @@ def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): observer.observe.assert_called_once_with(b'original output\n') observer.close.assert_called_once() + def test_stall_capture_falls_back_for_regular_file_input(self): + input_path = self.root / 'build-output.log' + input_path.write_bytes(b'original build output\n') + observer = Mock() + destination = io.BytesIO() + with patch.object(CAPTURE, 'MAX_LOG_BYTES', 8), patch.object( + CAPTURE, 'stall_marker') as marker, input_path.open('rb') as source: + status = CAPTURE.capture_log(source, destination, self.log, observer) + self.assertEqual(0, status) + self.assertEqual(b'original build output\n', destination.getvalue()) + self.assertEqual(b' output\n', self.log.read_bytes()) + marker.assert_called_once_with('observer-failed') + observer.observe.assert_not_called() + observer.close.assert_called_once() + + def test_stall_capture_registration_failure_closes_observer_without_hiding_read_error(self): + selector = Mock() + selector.register.side_effect = PermissionError('regular files cannot be epoll-registered') + observer = Mock() + + class BrokenSource: + def read(self, size): + raise OSError('direct read failed') + + with patch.object(CAPTURE.selectors, 'DefaultSelector', return_value=selector), patch.object( + CAPTURE, 'stall_marker') as marker, self.assertRaisesRegex(OSError, 'direct read failed'): + list(CAPTURE.capture_chunks(BrokenSource(), observer)) + selector.close.assert_called_once() + observer.close.assert_called_once() + marker.assert_called_once_with('observer-failed') + def test_module_wrapper_uses_two_workers_including_fallback(self): for module, partition, expected in [('account-service', '4', [2, 2]), ('account-service', 'full', [2]), diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 399954a797..b0948999a6 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -351,7 +351,16 @@ def capture_chunks(source, observer): yield chunk return selector = selectors.DefaultSelector() - selector.register(source, selectors.EVENT_READ) + try: + selector.register(source, selectors.EVENT_READ) + except OSError: + selector.close() + stall_marker('observer-failed') + observer.close() + reader = getattr(source, 'read1', source.read) + while chunk := reader(64 * 1024): + yield chunk + return try: while True: observer.tick() From 47d783467679e5575133475ad158fb1f99ba6874 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 15:03:01 +1300 Subject: [PATCH 59/66] Keep committed JOIN replay admission truthful to current tenant policy --- .../run-player-experience-smoke.py | 3 +- ...player-experience-smoke-runner-contract.sh | 5 +- .../service/impl/AccountServiceImpl.java | 7 +- .../service/impl/AccountServiceImplTest.java | 92 +++++++++++++++++++ 4 files changed, 101 insertions(+), 6 deletions(-) diff --git a/dev-tools/observability/run-player-experience-smoke.py b/dev-tools/observability/run-player-experience-smoke.py index aafe50030a..e42cf6ec74 100644 --- a/dev-tools/observability/run-player-experience-smoke.py +++ b/dev-tools/observability/run-player-experience-smoke.py @@ -2114,7 +2114,8 @@ def require_visible_world(config: SmokeConfig, bootstrap_token: str) -> None: ): return raise ProbeOperationalFailure( - f"World {config.world!r} was not visible during bootstrap discovery" + f"World {config.world!r} for tenant {config.tenant_slug!r} " + "was not visible during bootstrap discovery" ) diff --git a/dev-tools/tests/player-experience-smoke-runner-contract.sh b/dev-tools/tests/player-experience-smoke-runner-contract.sh index e43903cace..6d27e40a62 100644 --- a/dev-tools/tests/player-experience-smoke-runner-contract.sh +++ b/dev-tools/tests/player-experience-smoke-runner-contract.sh @@ -195,8 +195,9 @@ with patch.object(runner_module, "http_request_json", return_value={"data": [ ]}) as request: try: runner_module.require_visible_world(qualified, "bootstrap") - except runner_module.ProbeOperationalFailure: - pass + except runner_module.ProbeOperationalFailure as exc: + assert qualified.world in str(exc) + assert qualified.tenant_slug in str(exc) else: raise AssertionError("Another tenant's world satisfied discovery") with patch.object(runner_module, "http_request_json", return_value={"data": [ 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 d41891ebd7..5527b0423b 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 @@ -712,9 +712,10 @@ private CanonicalJoinResult commitCanonicalJoin( return new CanonicalJoinResult( committed.outcome(), committed.terminalProof(), - currentMembership - .map(AccountTenantMembership::isGameplayAdmissionAllowed) - .orElse(false), + gameplayAvailable + && currentMembership + .map(AccountTenantMembership::isGameplayAdmissionAllowed) + .orElse(false), true); } AccountTenantMembership committedMembership = currentMembership.orElseThrow(); 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 767b0a0600..ee0851233d 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 @@ -60,12 +60,15 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository; import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; @@ -918,6 +921,7 @@ void canonicalConcurrentCommitUsesLockedReplayStateAndStillChecksCurrentPolicy(b assertTrue(result.replayed()); assertTrue(result.success()); assertEquals("JOINED", result.outcomeCode()); + assertEquals(gameplay, result.gameplayAdmissionAllowed()); org.mockito.Mockito.verify(f.demos).revalidate(f.demo); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) .finishCanonicalFailure( @@ -927,6 +931,94 @@ void canonicalConcurrentCommitUsesLockedReplayStateAndStillChecksCurrentPolicy(b .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); } + @ParameterizedTest + @ValueSource(strings = {"demo", "paid"}) + void canonicalCommittedReplayPreservesReceiptWhenCurrentGameplayIsUnavailable(String sourceKind) { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("COMMITTED"); + f.joined.set(true); + f.currentMembership.setMembershipVersion(9L); + f.currentMembership.setMembershipAuthorityGeneration(4L); + f.currentMembership.setGameplayAdmissionAllowed(true); + var originalProof = f.committed.terminalProof(); + AccountHostingSubscriptionLifecycleRepository.ReadFence paidFence = null; + + if ("paid".equals(sourceKind)) { + when(f.source.kind()).thenReturn(SourceKind.PAID_HOSTING); + paidFence = + org.mockito.Mockito.mock(AccountHostingSubscriptionLifecycleRepository.ReadFence.class); + var receipt = org.mockito.Mockito.mock(AccountHostingSubscriptionCurrentReceipt.class); + when(f.hosting.prepareCurrentRead(f.scope.tenantId())).thenReturn(paidFence); + when(f.hosting.readCurrent( + org.mockito.ArgumentMatchers.eq(paidFence), org.mockito.ArgumentMatchers.isNull())) + .thenReturn(receipt); + when(receipt.gameplayAvailable()).thenReturn(false); + when(receipt.allowPublicJoin()).thenReturn(true); + when(receipt.entitlementVersion()).thenReturn(1L); + when(f.terminal.commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(f.scope), + org.mockito.ArgumentMatchers.eq(f.requestId), + org.mockito.ArgumentMatchers.eq(f.binding), + org.mockito.ArgumentMatchers.eq(f.hosting), + org.mockito.ArgumentMatchers.eq(paidFence), + org.mockito.ArgumentMatchers.isNull())) + .thenReturn(f.committed); + } else { + when(f.demo.gameplayAvailable()).thenReturn(false); + } + + var result = f.browserJoin(); + + assertTrue(result.success()); + assertTrue(result.replayed()); + assertEquals("JOINED", result.outcomeCode()); + assertEquals("JOINED", f.committed.outcome()); + assertSame(originalProof, f.committed.terminalProof()); + assertEquals(originalProof.membershipId(), result.membershipId()); + assertEquals(originalProof.membershipVersion(), result.membershipVersion()); + assertEquals( + originalProof.membershipAuthorityGeneration(), result.membershipAuthorityGeneration()); + assertFalse(result.gameplayAdmissionAllowed()); + assertTrue(f.currentMembership.isGameplayAdmissionAllowed()); + assertEquals(701L, f.currentMembership.getId()); + assertEquals("ACTIVE", f.currentMembership.getLifecycleState()); + assertEquals(9L, f.currentMembership.getMembershipVersion()); + assertEquals(4L, f.currentMembership.getMembershipAuthorityGeneration()); + + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin( + f.scope, + f.requestId, + f.binding, + "paid".equals(sourceKind) ? f.hosting : null, + paidFence, + null); + if ("paid".equals(sourceKind)) { + org.mockito.Mockito.verify(f.hosting).prepareCurrentRead(f.scope.tenantId()); + org.mockito.Mockito.verify(f.observer).observe(org.mockito.ArgumentMatchers.isNull()); + org.mockito.Mockito.verify(f.hosting) + .readCurrent(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.isNull()); + verifyNoInteractions(f.demos); + } else { + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + verifyNoInteractions(f.hosting, f.observer); + } + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountAuditOutboxRepository); + } + @Test void canonicalCommittedAlreadyActiveRetryPreservesReceiptAfterMembershipBecomesInactive() { var f = canonicalJoinFixture(); From ea8a0a0c8206e0e383a364216cf7f6cee7d1163d Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 20:42:03 +1300 Subject: [PATCH 60/66] Pass bounded canonical PLAY transition CI without publishing images --- .../workflows/publish-pr-runtime-images.yml | 11 +++ .github/workflows/runtime-images.yml | 27 ++++-- .github/workflows/smoke.yml | 68 +++++++++++-- .../architecture/system-architecture-cicd.md | 6 +- .../player-access-and-session.md | 2 +- .../pr-required-gate-context-contract.sh | 97 +++++++++++++++---- .../pr-runtime-image-publication-contract.sh | 21 +++- 7 files changed, 188 insertions(+), 44 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index e0f6e6c322..06ac261cdd 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -97,6 +97,16 @@ jobs: } if (run.status === "completed") { if (run.conclusion !== "success") throw new Error("publication source run did not succeed"); + const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRun, { + ...context.repo, run_id: sourceId, per_page: 100, + }); + if (jobs.some(job => job.name === "PR Full-Stack Smoke (runtime-required=true)" && + (job.steps ?? []).some(step => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" && + step.status === "completed" && step.conclusion === "success"))) { + core.notice("CI passed under the canonical PLAY transition exception; no runtime images are eligible for publication."); + return; + } core.setOutput("source", JSON.stringify(run)); core.setOutput("title", run.display_title); core.setOutput("artifact_name", `pr-runtime-images-pr-merge-${title[4]}`); @@ -112,6 +122,7 @@ jobs: publish: name: Publish Fixed PR Merge Image Tags needs: [source] + if: ${{ needs.source.outputs.source != '' }} concurrency: group: publish-pr-merge-images-${{ needs.source.outputs.title }} cancel-in-progress: false diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index c0726402e0..ea2804fecd 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1531,6 +1531,8 @@ jobs: create-storage-record: false pr-local-smoke: + outputs: + publishable: ${{ steps.runtime-artifact.outcome == 'success' }} name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) needs: [image-meta] if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} @@ -1642,6 +1644,8 @@ jobs: - name: Run credential-free full-stack smoke id: runtime-smoke + # The terminal guard admits only the classified, labeled transition failure. + continue-on-error: true if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} env: FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held @@ -1652,6 +1656,7 @@ jobs: run: bash ./dev-tools/verify-smoke-images.sh --keep-running - name: Export fixed-tag preview image artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} run: | service_manifest=/tmp/pr-runtime-services.txt provenance=/tmp/pr-runtime-provenance.json @@ -1717,6 +1722,8 @@ jobs: docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz - name: Upload preview image artifact + id: runtime-artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} @@ -1728,6 +1735,7 @@ jobs: retention-days: 1 - name: Summarize secure PR runtime artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} env: PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} @@ -1750,7 +1758,7 @@ jobs: - name: Dump Docker Compose logs on failure if: >- - ${{ failure() && + ${{ always() && steps.runtime-smoke.outcome == 'failure' && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.minio-source.outputs.server_image_id != '' && steps.minio-source.outputs.client_image_id != '' }} @@ -1791,8 +1799,9 @@ jobs: fi # Canonical-transition diagnostic evidence, not runtime qualification. The - # original failed step and the final required-smoke failure remain red. + # native smoke outcome remains failed; only the bounded CI exception may pass. - name: Known canonical transition PLAY failure with successful authenticated cleanup + id: canonical-play-transition if: >- ${{ always() && github.repository == 'benhook1013/FireMUD' && @@ -1816,16 +1825,22 @@ jobs: RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} with: script: | const required = process.env.RUNTIME_SMOKE_REQUIRED; if (required !== "true" && required !== "false") { core.setFailed("Runtime smoke scope is unavailable or invalid."); } else if (required === "true" && ( - process.env.RUNTIME_SMOKE_OUTCOME !== "success" || - process.env.RUNTIME_CLEANUP_OUTCOME !== "success" + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || + (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( + process.env.RUNTIME_SMOKE_OUTCOME === "failure" && + process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" + )) )) { - core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully."); + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); + } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); } pr-controller-smoke: @@ -1898,7 +1913,7 @@ jobs: dispatch-pr-runtime-publication: name: Dispatch Trusted PR Runtime Publication needs: [image-meta, pr-local-smoke, pr-controller-smoke] - if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 681381a02e..a4bc626f22 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,9 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; + const canonicalRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; + // Retain the exact fail-red producer still executed by trusted base refreshes. + const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", @@ -771,6 +773,9 @@ jobs: job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== "success" || job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` ) return false; + const markers = (job.steps ?? []).filter((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" + ); // PR workflows execute their test merge definition; typed refreshes execute the // immutable default-branch revision recorded by their native run attempt. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; @@ -782,8 +787,11 @@ jobs: definition.encoding !== "base64" || typeof definition.content !== "string") return false; const bytes = Buffer.from(definition.content, "base64"); if (definition.size !== bytes.length) return false; - if (require("node:crypto").createHash("sha256").update(bytes).digest("hex") !== - canonicalRuntimeWorkflowSha256) return false; + const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); + if (definitionHash === canonicalRuntimeWorkflowSha256) { + if (markers.length !== 1 || markers[0].status !== "completed" || + markers[0].conclusion !== "skipped") return false; + } else if (definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) @@ -807,7 +815,7 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; if ( source.id !== run.id || source.run_attempt !== run.run_attempt || - source.status !== "completed" || source.conclusion !== "failure" || + source.status !== "completed" || !["success", "failure"].includes(source.conclusion) || source.path !== workflowPath || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event @@ -840,10 +848,10 @@ jobs: if ( !positiveInteger(job.id) || job.id !== candidate.id || job.run_id !== source.id || job.run_attempt !== source.run_attempt || - job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== "failure" || + job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== source.conclusion || job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` ) return false; - const expectedFailures = [ + const expectedSuccessfulSteps = [ "Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup", ]; @@ -855,17 +863,18 @@ jobs: if (!exactlyOne(markerName, "success") || !exactlyOne("Stop smoke stack", "success") || !exactlyOne("Export fixed-tag preview image artifact", "skipped") || !exactlyOne("Upload preview image artifact", "skipped") || - expectedFailures.some((name) => !exactlyOne(name, "failure")) || + expectedSuccessfulSteps.some((name) => !exactlyOne(name, source.conclusion)) || steps.some((step) => step.status !== "completed" || !["success", "skipped", "failure"].includes(step.conclusion) || - (step.conclusion === "failure" && !expectedFailures.includes(step.name))) || + (step.conclusion === "failure" && !(source.conclusion === "failure" && expectedSuccessfulSteps.includes(step.name)))) || jobs.some((other) => other.id !== job.id && (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; // Typed refresh workflow authority is its native default-branch revision; // the executed classifier source still belongs to the verified PR merge. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; for (const [path, expectedSha256] of Object.entries({ - [workflowPath]: canonicalRuntimeWorkflowSha256, + [workflowPath]: source.conclusion === "failure" + ? canonicalLegacyRuntimeWorkflowSha256 : canonicalRuntimeWorkflowSha256, ...canonicalPlayClassifierSha256, })) { const { data: definition } = await withTransientGitHubRetry( @@ -886,7 +895,7 @@ jobs: () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) ); if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || - latest.status !== "completed" || latest.conclusion !== "failure") return false; + latest.status !== "completed" || latest.conclusion !== source.conclusion) return false; // The fingerprinted marker attests the PR event label or the typed // refresh's verified live PR label. Removal closes either exception. const { data: currentPullRequest } = await withTransientGitHubRetry( @@ -1358,6 +1367,45 @@ jobs: return; } + // A continued probe has API conclusion=success even when its native + // outcome failed. The immutable marker distinguishes that exception. + if (fullSmokeJob?.name === canonicalSmokeJobName) { + const markers = (fullSmokeJob.steps ?? []).filter((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" + ); + if (markers.length === 1 && markers[0].status === "completed" && + markers[0].conclusion === "success") { + let knownPlayVerified = false; + try { + knownPlayVerified = await verifyKnownPlayFailure(matching, fullSmokeJob, currentIdentity); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); + } + if (!knownPlayVerified) { + core.setFailed("Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."); + return; + } + const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); + if (freshIdentity?.obsolete) return; + if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { + currentIdentity = freshIdentity; + continue smokeGatePolling; + } + core.setOutput("known_play_exception", "true"); + core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); + await core.summary.addHeading("Canonical PLAY transition exception accepted") + .addRaw("Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Held-admission qualification and authenticated cleanup passed. CI passed under exception; no runtime qualification, image export, or publication.") + .write(); + return; + } + if (!canonicalProducerVerified && (markers.length !== 1 || + markers[0].status !== "completed" || markers[0].conclusion !== "skipped")) { + core.setFailed("Runtime smoke proof is missing its unambiguous transition-exception disposition."); + return; + } + } + if (fullSmokeJob?.conclusion !== "success") { if (await isCurrentPullRequestObsolete("Stopping obsolete failed full-smoke gate for")) { return; diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 7ca758de50..e92de2b824 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -84,13 +84,13 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required Smoke Gate accepts a successful credential-free smoke run for its verified PR-event base/head/merge tuple. If GitHub supplies no usable event merge SHA or the event base SHA already lags the event merge's parents, the gate instead requires a successful trusted, typed refresh for the verified current base/head/merge tuple. An unrelated base advance after valid event-tuple smoke does not invalidate that tested merge or require the PR head to absorb new dependencies; a changed PR head or base branch requires new proof. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. The credential-free runtime producer and required Smoke Gate cover every PR base, including same-repository feature branches, while retaining runtime path classification and an explicit no-op for irrelevant changes. Hosted preview and registry publication retain their separate eligibility policy: a stacked pull request requires the maintainer-controlled `preview:priority` label, an open mergeable state, and a current same-repository base. Completed Validation callbacks qualify long-lived branch pushes or substantive same-repository PR heads against the current branch ref before dispatching child-specific exact base/head/merge runtime refreshes. PR callbacks verify the current native CI attempt and executed substantive enforcement with skipped metadata preservation before reconciling their source PR's current tuple, recovering retarget edits whose event merge cannot qualify. Metadata-only, superseded, or unclassifiable attempts do not reconstruct runtime. PR-completion reconciliation is isolated by source run ID and attempt, so a metadata completion cannot cancel a substantive refresh; protected branch publication retains its separate branch serialization. Dependent refresh for `main` and `develop` belongs only to their push callback; PR callbacks whose head is one of those branches still reconcile their own source PR. A stale parent callback cannot dispatch proof for an advanced branch, and the callback itself supplies no child smoke proof. Preview reconciliation is dispatched only for independently eligible targets; scheduled preview reconciliation remains an additional recovery path. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own held-admission qualification succeeds and the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. -A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. +A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed and its image artifact upload succeeds; an exception pass with no uploaded artifact cannot dispatch publication. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest failed producer attempt while the PR head and base branch remain current. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke and terminal guard failures remain visible; unrelated failures still block, and image export and upload must be skipped. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. -The step-independent producer guarantee is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. +The producer guarantee, independent of smoke-step metadata but requiring an explicit skipped exception marker, is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. Branch-to-environment promotion 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 5340479c96..67eb8aee7d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ Account initial/current/final creation owners, explicit initial billing-owner co ### Temporary canonical PLAY transition exception -The explicitly approved nonproduction canonical-cutover scope has a [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), gated by the `canonical-play-transition` label and fresh evidence for the exact current PR tuple. The label does not authorize expanding that approved scope. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The producer remains failed and branch-image publication is blocked by real smoke. Repair Account entitlement and obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. This is nonproduction merge-gate accommodation, not activation authority. +The explicitly approved nonproduction canonical-cutover scope has a [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), gated by the `canonical-play-transition` label and fresh evidence for the exact current PR tuple. The label does not authorize expanding that approved scope. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The probe retains its failed Actions-native outcome and exact classified error. Runtime CI and Smoke Gate may pass under the bounded exception after successful authenticated cleanup; their summaries explicitly report that runtime qualification is absent. Image export, upload, typed publication handoff and trusted publication remain blocked for an exception attempt. Repair the canonical Account PLAYER_ADMISSION receiving chain and its Game Session PLAY consumer, then obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. The integrated stack still leaves the canonical receiver unregistered and numeric PLAY entitlement reads denied; merely registering that receiver or restoring numeric subscription reads does not complete this obligation. This is nonproduction merge-gate accommodation, not activation authority. ### Direct-text scope and JOIN identifier cutover diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 6926901890..4a6bad2355 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -574,8 +574,14 @@ steps = producer_job["steps"] smoke_step = next(step for step in steps if step.get("id") == "runtime-smoke") cleanup_step = next(step for step in steps if step.get("id") == "runtime-cleanup") guard = steps[-1] -if any(step.get("continue-on-error") not in (None, "false") for step in (smoke_step, cleanup_step, guard)): - raise SystemExit("Runtime smoke, cleanup, and terminal guard cannot ignore failures") +if smoke_step.get("continue-on-error") != "true": + raise SystemExit("Probe failure must reach the exact transition terminal guard") +if any(step.get("continue-on-error") not in (None, "false") for step in (cleanup_step, guard)): + raise SystemExit("Cleanup and terminal enforcement cannot ignore failures") +for name in ("Export fixed-tag preview image artifact", "Upload preview image artifact", "Summarize secure PR runtime artifact"): + artifact = next(step for step in steps if step.get("name") == name) + if artifact.get("if") != "${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }}": + raise SystemExit("Failed probe must never export, upload or summarize publishable images") if smoke_step["run"] != "bash ./dev-tools/verify-smoke-images.sh --keep-running": raise SystemExit("Native smoke outcome must belong to the canonical smoke invocation") if guard["if"] != "${{ always() }}" or guard["name"] != "Require successful runtime smoke and authenticated cleanup": @@ -584,6 +590,7 @@ if guard["env"] != { "RUNTIME_SMOKE_REQUIRED": "${{ needs.image-meta.outputs.runtime_smoke_required }}", "RUNTIME_SMOKE_OUTCOME": "${{ steps.runtime-smoke.outcome }}", "RUNTIME_CLEANUP_OUTCOME": "${{ steps.runtime-cleanup.outcome }}", + "KNOWN_PLAY_EXCEPTION_OUTCOME": "${{ steps.canonical-play-transition.outcome }}", }: raise SystemExit("Terminal guard must consume native Actions outcomes, never command-written outputs") Path(sys.argv[2] + ".guard").write_text(guard["with"]["script"]) @@ -773,6 +780,19 @@ for (const required of ["false", "", "unknown"]) { guard({env: {RUNTIME_SMOKE_REQUIRED: required}}, {setFailed: message => failures.push(message)}); assert.equal(failures.length === 0, required === "false"); } +for (const smoke of ["success", "failure", "skipped", "cancelled", ""]) { + for (const cleanup of ["success", "failure", "skipped", "cancelled", ""]) { + for (const marker of ["success", "failure", "skipped", ""]) { + const failures = [], warnings = []; + guard({env: {RUNTIME_SMOKE_REQUIRED: "true", RUNTIME_SMOKE_OUTCOME: smoke, + RUNTIME_CLEANUP_OUTCOME: cleanup, KNOWN_PLAY_EXCEPTION_OUTCOME: marker}}, + {setFailed: message => failures.push(message), warning: message => warnings.push(message)}); + const exception = smoke === "failure" && marker === "success" && cleanup === "success"; + assert.equal(failures.length === 0, cleanup === "success" && (smoke === "success" || exception)); + assert.equal(warnings.length, Number(exception)); + } + } +} const execute = new Function("github", "context", "core", "Date", "setTimeout", "require", `return (async () => {\n${script}\n})()`); const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40), defaultSha = "d".repeat(40); const repository = "example/firemud"; @@ -792,7 +812,10 @@ async function scenario(kind, event = "pull_request") { status: "completed", conclusion: "success", pull_requests: []}; const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, check_run_url: `https://api.github.com/repos/${repository}/check-runs/100`, - name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", steps: []}; + name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", + steps: [{name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", conclusion: "skipped"}]}; + if (kind === "marker-missing") job.steps = []; + if (kind === "marker-success") job.steps[0].conclusion = "success"; if (kind.startsWith("legacy")) job.name = "PR Full-Stack Smoke"; if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; @@ -860,7 +883,7 @@ async function scenario(kind, event = "pull_request") { assert.deepEqual(success.refs, [event === "pull_request" ? merge : defaultSha], "immutable definition must come from actual source event revision"); } assert.deepEqual((await scenario("legacy-positive")).failures, []); - for (const kind of ["legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", + for (const kind of ["marker-missing", "marker-success", "legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", "changed-definition", "unavailable-definition", "wrong-job", "wrong-job-run", "wrong-job-attempt", "wrong-job-head", "wrong-check-url", "failed-job", "pending-job", "duplicate-jobs", "duplicate-attempt-jobs", "newer-attempt", "bad-parents"]) { @@ -3433,6 +3456,8 @@ const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); +// Separate test authority lets the same verifier exercise both immutable modes. +const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".classifiers.json", "utf8")); const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); @@ -3441,12 +3466,12 @@ const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; const run = {id: 99, run_attempt: 2, event: "pull_request"}; const failures = ["Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup"]; const step = (name, conclusion) => ({name, conclusion, status: "completed"}); -const source = {...run, status: "completed", conclusion: "failure", path: workflowPath, +const source = {...run, status: "completed", conclusion: "success", path: workflowPath, repository: {full_name: repositoryName}, workflow_id: 7, head_repository: {full_name: repositoryName}, head_sha: headSha, display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${baseSha} head-${headSha} merge-${mergeSha} mode-required`}; const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: canonicalSmokeJobName, - status: "completed", conclusion: "failure", check_run_url: `https://api.github.com/repos/${repositoryName}/check-runs/123`, - steps: [...failures.map(name => step(name, "failure")), step("Stop smoke stack", "success"), + status: "completed", conclusion: "success", check_run_url: `https://api.github.com/repos/${repositoryName}/check-runs/123`, + steps: [...failures.map(name => step(name, "success")), step("Stop smoke stack", "success"), step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; async function verify(mutate = () => {}, event = "pull_request") { @@ -3479,21 +3504,39 @@ async function verify(mutate = () => {}, event = "pull_request") { return {data: data.definitions[path]}; }}}}; const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", - "canonicalRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", + "canonicalRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( - github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPlayClassifierSha256, + github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); if (accepted) assert.deepEqual(contentRequests, [workflowPath, ...Object.keys(classifierDefinitions)]); return accepted; } -// Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. -const failedStart = script.indexOf('if (matching.conclusion !== "success")'); -const failedEnd = script.indexOf("const latestIdentity", failedStart); +// Proof errors in a successful exception attempt must fail closed. +const failedStart = script.indexOf('// A continued probe'); +const failedEnd = script.indexOf('if (fullSmokeJob?.conclusion !== "success")', failedStart); const failedBranch = script.slice(failedStart, failedEnd); class TerminalGitHubRequestError extends Error {} -async function failedProof(stage, error, event = "pull_request") { +async function failedProof(error, event = "pull_request") { + const warnings = [], failures = [], outputs = []; + const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), + setOutput: (...value) => outputs.push(value)}; + const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", + "verifyKnownPlayFailure", "TerminalGitHubRequestError", "core", + `return (async () => { smokeGatePolling: while (true) { ${failedBranch} break; } })();`); + await execute(candidate, {...source, event}, canonicalSmokeJobName, identity, + async () => {throw error;}, TerminalGitHubRequestError, core); + assert.deepEqual(failures, ["Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."]); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); + assert.deepEqual(outputs, []); +} +// Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. +const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); +const legacyFailedEnd = script.indexOf("const latestIdentity", legacyFailedStart); +const legacyFailedBranch = script.slice(legacyFailedStart, legacyFailedEnd); +async function failedLegacyProof(stage, error, event = "pull_request") { const warnings = [], failures = [], outputs = []; const github = {paginate: async () => { if (stage === "jobs") throw error; @@ -3504,8 +3547,8 @@ async function failedProof(stage, error, event = "pull_request") { const execute = new Function("matching", "repositoryName", "github", "owner", "repo", "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", - `return (async () => { smokeGatePolling: while (true) { ${failedBranch} break; } })();`); - await execute({...source, event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, + `return (async () => { smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); + await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, TerminalGitHubRequestError, core); assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); @@ -3534,13 +3577,18 @@ function markerAccepted(overrides = {}) { (async () => { for (const event of ["pull_request", "repository_dispatch"]) { for (const stage of ["jobs", "proof", "malformed-jobs"]) { - await failedProof(stage, Object.assign(new Error("unavailable"), {status: 404}), event); + await failedLegacyProof(stage, Object.assign(new Error("unavailable"), {status: 404}), event); } } - await failedProof("proof", null); + await failedLegacyProof("proof", null); + for (const event of ["pull_request", "repository_dispatch"]) { + await failedProof(Object.assign(new Error("unavailable"), {status: 404}), event); + await failedProof(null, event); + } for (const stage of ["jobs", "proof"]) { const terminal = new TerminalGitHubRequestError("permission denied"); - await assert.rejects(failedProof(stage, terminal), error => error === terminal); + await assert.rejects(failedLegacyProof(stage, terminal), error => error === terminal); + await assert.rejects(failedProof(terminal), error => error === terminal); } assert.equal(markerAccepted(), true); const refreshMarker = {"github.event_name": "repository_dispatch", @@ -3565,6 +3613,13 @@ function markerAccepted(overrides = {}) { {"github.event_name": "workflow_run"}, ]) assert.equal(markerAccepted(overrides), false); assert.equal(await verify(), true); + for (const event of ["pull_request", "repository_dispatch"]) { + assert.equal(await verify(d => { + d.legacyDefinition = true; + d.source.conclusion = d.latest.conclusion = d.candidate.conclusion = "failure"; + for (const step of d.candidate.steps) if (failures.includes(step.name)) step.conclusion = "failure"; + }, event), true, "exact old fail-red default-branch producer remains a diagnostic exception only"); + } assert.equal(await verify(() => {}, "repository_dispatch"), true); for (const path of Object.keys(classifierDefinitions)) { assert.equal(await verify(d => { @@ -3598,7 +3653,7 @@ function markerAccepted(overrides = {}) { d => {d.source.event = "workflow_run";}, d => {d.source.run_attempt = 1;}, d => {d.latest.run_attempt = 3; assert.equal(d.source.run_attempt, 2);}, - d => {d.latest.conclusion = "success"; assert.equal(d.source.conclusion, "failure");}, + d => {d.latest.conclusion = "failure"; assert.equal(d.source.conclusion, "success");}, d => {d.source.path = ".github/workflows/spoof.yml";}, d => {d.source.repository.full_name = "attacker/FireMUD";}, d => {d.definitions[workflowPath].content = Buffer.from("spoof").toString("base64"); d.definitions[workflowPath].size = 5;}, @@ -3610,7 +3665,9 @@ function markerAccepted(overrides = {}) { d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Known canonical transition"));}, d => {d.jobs[0].steps.find(s => s.name.startsWith("Export fixed")).conclusion = "success";}, d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Export fixed"));}, - d => {d.source.conclusion = "success";}, + d => {d.source.conclusion = "failure";}, + d => {d.jobs[0].steps.find(s => s.name === "Run credential-free full-stack smoke").conclusion = "failure";}, + d => {d.jobs[0].steps.find(s => s.name === "Require successful runtime smoke and authenticated cleanup").conclusion = "failure";}, d => {d.jobs = [];}, d => {d.jobs[0].steps = [];}, d => {delete d.jobs[0].steps;}, diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index f045296465..803550a80f 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -181,14 +181,18 @@ const title = `Build Runtime Images secure-pr-artifact pr-42 base-${sha("b")} he const repository = { full_name: "benhook1013/FireMUD", default_branch: "develop" }; const source = { id: 4242, workflow_id: 777, path: ".github/workflows/runtime-images.yml", name: title, display_title: title, event: "repository_dispatch", repository, head_repository: repository, head_branch: "develop", head_sha: sha("b"), status: "completed", conclusion: "success" }; const baseContext = { eventName: "repository_dispatch", ref: "refs/heads/develop", repo: {owner: "benhook1013", repo: "FireMUD"}, runId: 4242, payload: { repository, action: "pr-runtime-image-publication", client_payload: { source_run_id: "4242" } } }; -async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false } = {}) { +async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false, jobs = [] } = {}) { let reads = 0, clock = 0; const output = {}; - const github = { rest: { actions: { + const github = { paginate: async () => jobs, rest: { actions: { getWorkflow: async () => ({data: workflow}), getWorkflowRun: async request => { assert.equal(request.run_id, 4242); reads++; if (error) throw Error("API unavailable"); return {data: runs[Math.min(reads - 1, runs.length - 1)]}; }, } } }; - await resolver(github, context, {setOutput: (key, value) => {output[key] = value;}}, {now: () => {clock += 60000; return clock;}}, fn => fn()); + await resolver(github, context, {notice: () => {}, setOutput: (key, value) => {output[key] = value;}}, {now: () => {clock += 60000; return clock;}}, fn => fn()); + if (jobs.some(job => (job.steps ?? []).some(step => step.conclusion === "success"))) { + assert.deepEqual(output, {}, "exception attempts must expose no publication source"); + return {reads, output}; + } assert.equal(output.title, title); assert.equal(output.artifact_name, `pr-runtime-images-pr-merge-${sha("c")}`); assert.equal(JSON.parse(output.source).status, "completed"); @@ -224,7 +228,7 @@ const handoffCondition = runtimeWorkflow.split(" dispatch-pr-runtime-publicatio .replace(/needs\.([a-z-]+)/g, (_, key) => `needs[${JSON.stringify(key)}]`); const admitted = new Function("github", "needs", "always", "cancelled", "format", `return ${handoffCondition};`); const trigger = {event_name: "repository_dispatch", event: {action: "pr-runtime-base-refresh", repository}, ref: "refs/heads/develop"}; -const success = {"image-meta": {result: "success", outputs: {controller_smoke_required: "false"}}, "pr-local-smoke": {result: "success"}, "pr-controller-smoke": {result: "skipped"}}; +const success = {"image-meta": {result: "success", outputs: {controller_smoke_required: "false"}}, "pr-local-smoke": {result: "success", outputs: {publishable: "true"}}, "pr-controller-smoke": {result: "skipped"}}; function admits(event = trigger, results = success, cancelled = false) { return admitted(event, results, () => true, () => cancelled, (pattern, value) => pattern.replace("{0}", value)); } @@ -237,6 +241,9 @@ for (const job of ["image-meta", "pr-local-smoke", "pr-controller-smoke"]) { assert.equal(admits(trigger, {...success, "image-meta": {result: "success", outputs: {controller_smoke_required: "true"}}}), false); assert.equal(admits(trigger, {...success, "image-meta": {result: "success", outputs: {}}}), false); assert.equal(admits(trigger, success, true), false); +for (const publishable of ["false", "", undefined]) { + assert.equal(admits(trigger, {...success, "pr-local-smoke": {result: "success", outputs: {publishable}}}), false); +} (async () => { for (const path of diagnosticPaths) { assert.equal(await smokeDecision([path]), "false", `${path} must not require runtime smoke`); @@ -252,6 +259,11 @@ assert.equal(admits(trigger, success, true), false); await dispatch({rest: {repos: {createDispatchEvent: async payload => {dispatched = payload;}}}}, baseContext); assert.deepEqual(dispatched, {...baseContext.repo, event_type: "pr-runtime-image-publication", client_payload: {source_run_id: "4242"}}); const direct = await resolve(); + const exceptionJob = {name: "PR Full-Stack Smoke (runtime-required=true)", steps: [{ + name: "Known canonical transition PLAY failure with successful authenticated cleanup", + status: "completed", conclusion: "success"}]}; + assert.deepEqual((await resolve({jobs: [exceptionJob]})).output, {}); + assert.equal((await resolve({jobs: [{...exceptionJob, steps: [{...exceptionJob.steps[0], conclusion: "skipped"}]}]})).output.title, title); const pending = {...source, status: "in_progress", conclusion: null}; assert.equal((await resolve({runs: [pending, source]})).reads, 2); const callbackContext = {...baseContext, eventName: "workflow_run", payload: {repository, workflow_run: source}}; @@ -263,6 +275,7 @@ assert.equal(admits(trigger, success, true), false); assert.equal((await resolve({runs: [prSource]})).output.artifact_name, direct.output.artifact_name); assert.equal((await resolve({runs: [prSource], context: prCallback})).output.artifact_name, direct.output.artifact_name); const publisherWorkflow = fs.readFileSync(process.argv[5], "utf8"); + assert.ok(publisherWorkflow.includes("if: ${{ needs.source.outputs.source != '' }}"), "no source must skip privileged publication"); const download = publisherWorkflow.split(" - name: Download successful PR image artifacts\n")[1] .split(" - name: Validate exact PR source and artifact before registry login\n")[0]; const inputs = Object.fromEntries([...download.matchAll(/^ (name|path|run-id): (.+)$/gm)] From 05dfdd6c5a45c6ffebec110e9a01ef484ada20c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:34:24 +1300 Subject: [PATCH 61/66] Retain JDK stall frames and clarify bootstrap selectors --- .../microservices/account-service/api-contracts.md | 4 ++-- dev-tools/tests/test_gradle_compile_failure.py | 7 ++++++- dev-tools/validation/collect-gradle-compile-failure.py | 4 ++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 522c02cb18..ee10b7d2a6 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -101,7 +101,7 @@ At effective expiry or revocation, Account publishes the monotonic grant-authori Each visible world returns its stable `tenantSlug` and tenant-scoped `worldSlug` with its display name. Different tenants may expose the same world slug; clients retain both selectors and pass `tenantSlug` as the required query parameter to `GET /auth/bootstrap/worlds/{worldSlug}/realms`. Account resolves the pair against one complete current discovery collection. A bare or globally inferred world selector is not a supported browser request. The resulting opaque `connectScopeId` binds the exact tenant and realm for subsequent character discovery and admission; the character route still verifies its world/realm path against that scope. -`ListBootstrapWorlds` returns the complete set of unambiguous visible public-production worlds whose current Account entitlement says gameplay is available. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug`, then `tenantSlug`, ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). +`ListBootstrapWorlds` returns the complete set of visible public-production tenant-qualified world selectors whose current Account entitlement says gameplay is available. The whole request fails if the collection represents one canonical tenant more than once; shared world slugs across different tenants remain valid. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug`, then `tenantSlug`, ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Independent tenant entitlement evaluations run outside ambient SQL with at most eight concurrent workers per discovery request. A shared fair eight-permit bound also limits active evaluations across all discovery requests and owner instances in the Account process. Waiting for a permit occurs outside SQL and lasts at most five seconds; contention expiry fails the whole discovery request as `ENTITLEMENT_UNAVAILABLE`. Success, source failure and interruption return acquired permits. This bounds this owner’s aggregate connection demand without resizing the Account pool or guaranteeing production capacity. Each tenant is evaluated once and retains its owner’s independent transaction/isolation checks; caller and SQL context are not propagated to workers. The owner waits for the complete set, validates every returned tenant identity and returns no partial result on failure or interruption. Original observation deadlines remain unchanged and are checked after the second complete target read and final caller check. This bound reduces serialized latency; it is not a production capacity guarantee or permission to extend expired evidence, and slow or large collections can still refuse when their original observations expire. @@ -232,7 +232,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - 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. The legacy `LinkExternalAccount` gRPC adapter returns `FAILED_PRECONDITION` before parsing, lookup or mutation. 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. +- `ListBootstrapRealms` – list caller-visible realms for a tenant-qualified world selected by `tenantSlug` and `worldSlug` during first-party gameplay bootstrap. - `IssueDirectTextConnectScope` – prepared internal Account API; with the default scope producer absent, the receiving method returns `AUTH_UNAVAILABLE`. When manually configured, it delegates to the scope owner for caller/target validation and scope issuance. Game Session text `REALMS` dispatch remains pending under #2898. Current held status, preserved source obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); the target scope and transport contract remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 1f67bfe12b..5c500b07bf 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -218,7 +218,9 @@ def test_stall_daemon_retains_late_frames_with_fixed_larger_ceiling(self): def test_stall_sanitizer_rejects_names_secrets_and_diagnostic_prose(self): raw = (b'"SECRET-password" #17 tid=0xabc nid=0xdef waiting\n' b' java.lang.Thread.State: WAITING (parking)\n' - b' at java.base@25/java.lang.Object.wait0(Native Method)\n' + b' at java.lang.Object.wait0(java.base@25/Native Method)\n' + b' at jdk.internal.misc.Unsafe.park(java.base@25.0.5+8/Native Method)\n' + b'\"SECRET-decimal-thread\" #18 tid=0x123 nid=345 waiting\n' b' at org.example.Work.run(Work.java:42)\n' b' - locked <0xabc> (a java.lang.Object)\n' b'JAVA_TOOL_OPTIONS=SECRET\njdbc:postgresql://SECRET\n' @@ -226,6 +228,9 @@ def test_stall_sanitizer_rejects_names_secrets_and_diagnostic_prose(self): output = CAPTURE.sanitized_threads(raw) self.assertNotIn('SECRET', output) self.assertIn('#17 tid=0xabc nid=0xdef', output) + self.assertIn('#18 tid=0x123 nid=345', output) + self.assertIn('Object.wait0(java.base@25/Native Method)', output) + self.assertIn('Unsafe.park(java.base@25.0.5+8/Native Method)', output) self.assertIn('WAITING', output) self.assertIn('Work.run(Work.java:42)', output) self.assertIn('locked <0xabc>', output) diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index b0948999a6..1354b452b6 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -183,10 +183,10 @@ def sanitized_threads(raw): lines = [] for line in raw.decode('utf-8', errors='replace').splitlines(): if line.startswith('"'): - identifiers = re.findall(r'(?:#\d+|(?:tid|nid)=0x[0-9a-f]+)(?=\s|$)', line[line.rfind(chr(34)) + 1:]) + identifiers = re.findall(r'(?:#\d+|tid=0x[0-9a-f]+|nid=(?:0x[0-9a-f]+|[0-9]+))(?=\s|$)', line[line.rfind(chr(34)) + 1:]) lines.append('thread (name omitted) ' + ' '.join(identifiers)) elif (re.fullmatch(r'\s*java.lang.Thread.State: [A-Z_]+(?: \([a-z ]+\))?', line) - or re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$: /\-]+\)', line) + or re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$:@+ /\-]+\)', line) or re.fullmatch(r'\s*- (?:locked|waiting on|waiting to lock|parking to wait for)\s+<0x[0-9a-f]+> \(a [A-Za-z0-9_.$]+\)', line)): lines.append(line.strip()) return '\n'.join(lines) From 14a8223c471df3233e17346f29975ce9b177e4c2 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 21:45:02 +1300 Subject: [PATCH 62/66] Align direct scope session correlation with JOIN --- ...AccountCanonicalPublicRealmScopeOwner.java | 10 ++- ...untCanonicalPublicRealmScopeOwnerTest.java | 88 ++++++++++++++++++- 2 files changed, 93 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index 70a1aaf7fd..8125edd084 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -147,19 +147,21 @@ public RealmScope issueDirectTextScope( || caller.requestId() == null || caller.sessionId().isBlank() || caller.requestId().isBlank() - || caller.sessionId().length() > 128 + || caller.sessionId().length() > 32 || caller.requestId().length() > 128) { throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "Direct caller correlation is invalid"); } try { - long session = Long.parseLong(caller.sessionId()); - if (session <= 0 || !caller.sessionId().matches("[0-9]+")) { + if (!caller.sessionId().matches("[0-9]+")) { + throw new NumberFormatException("Invalid transport session"); + } + if (Long.parseLong(caller.sessionId()) <= 0) { throw new NumberFormatException("Invalid transport session"); } } catch (NumberFormatException failure) { throw new AuthenticationException( - "CONNECT_CONTEXT_INVALID", "Direct caller session is invalid"); + "CONNECT_CONTEXT_INVALID", "Direct caller session is invalid", failure); } // These times describe this Account producer invocation, not a fabricated bootstrap lifetime. Instant issuedAt = now(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 9cd28712c3..7765522719 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -111,6 +111,88 @@ void directProducerUsesExactGameSessionPeerAndCurrentOwnersWithoutBootstrapRegis verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); } + @ParameterizedTest + @ValueSource(strings = {"00042", "00000000000000000000000000000042", "9223372036854775807"}) + void directProducerAcceptsPositiveSessionBytesWithinTheJoinBoundary(String sessionId) { + Fixture f = new Fixture(300000L); + directPeer(NAMESPACE, "game-session-service") + .run( + () -> { + var scope = + f.owner + .issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target)) + .scope(); + assertThat(scope.accountId()).isEqualTo(ACCOUNT); + assertThat(f.retained.get()).isEqualTo(scope); + verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); + }); + } + + @ParameterizedTest + @ValueSource(ints = {33, 128, 129}) + void directProducerRefusesSessionBytesBeyondTheJoinBoundaryBeforeOwnerReads(int length) { + Fixture f = new Fixture(300000L); + String sessionId = "0".repeat(length - 1) + "1"; + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "CONNECT_CONTEXT_INVALID", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target)))); + verifyNoInteractions( + f.accounts, + f.memberships, + f.tenants, + f.heads, + f.scopes, + f.sessions, + f.targets, + f.entitlements); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0", + "-1", + "+1", + " 42", + "42 ", + "1.0", + "1e2", + "abc", + "9223372036854775808", + "\u0664\u0662", + "\uff14\uff12" + }) + void directProducerRefusesNonPositiveAsciiLongsAndRetainsParseCauseBeforeOwnerReads( + String sessionId) { + Fixture f = new Fixture(300000L); + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertThatThrownBy( + () -> + f.owner.issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target))) + .isInstanceOf(AuthenticationException.class) + .hasCauseInstanceOf(NumberFormatException.class) + .extracting(failure -> ((AuthenticationException) failure).getCode()) + .isEqualTo("CONNECT_CONTEXT_INVALID")); + verifyNoInteractions( + f.accounts, + f.memberships, + f.tenants, + f.heads, + f.scopes, + f.sessions, + f.targets, + f.entitlements); + } + @ParameterizedTest @ValueSource(strings = {"other-namespace", "wrong-service"}) void directProducerRefusesWrongPeerBeforeReadingAccountOrSources(String mismatch) { @@ -218,6 +300,10 @@ private static io.grpc.Context directPeer(String namespace, String service) { } private static DirectTextCallerContext directCaller(Target target) { + return directCaller(target, "00042"); + } + + private static DirectTextCallerContext directCaller(Target target, String sessionId) { return new DirectTextCallerContext( ACCOUNT, target.canonicalTenantId(), @@ -225,7 +311,7 @@ private static DirectTextCallerContext directCaller(Target target) { target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), - "00042", + sessionId, "direct-request"); } From 51b03df5cd4afb77a9e35bc09c9063102f3cd9cd Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 21:45:02 +1300 Subject: [PATCH 63/66] Recover pinned Gradle distribution downloads through official asset API --- .github/workflows/ci.yml | 12 +- .github/workflows/runtime-images.yml | 7 +- .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 1 + .../gradle-dependency-recovery-contract.sh | 164 ++++++++++++++++++ .../run-gradle-with-dependency-recovery.sh | 143 +++++++++++++++ 6 files changed, 319 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0389908fe9..d228afc118 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -250,7 +250,7 @@ jobs: - name: Compile the actual Buf-generated Java sources run: | test -n "$(find protos/gen/java -name '*.java' -print -quit)" - ./gradlew compileBufGeneratedJava + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- compileBufGeneratedJava docker-lint: name: Dockerfile Lint @@ -681,7 +681,7 @@ jobs: - name: 🧪 Check Flyway Migration Versions env: FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} - run: ./gradlew checkFlywayVersions + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkFlywayVersions grpc-transport-config-sanity-checks: name: gRPC Transport Configuration Sanity Checks @@ -717,7 +717,7 @@ jobs: cache-read-only: false - name: 🧪 Check gRPC Transport Configuration - run: ./gradlew checkGrpcTransportConfig checkGrpcPublicMethods + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkGrpcTransportConfig checkGrpcPublicMethods workflow-lint: name: GitHub Workflow Lint @@ -1133,7 +1133,7 @@ jobs: - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) && (matrix.module != 'account-service' && matrix.module != 'game-session-service' || matrix.partition == '1') }} - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck - name: 📈 Parse Coverage % id: coverage @@ -1330,7 +1330,7 @@ jobs: cache-read-only: false - name: Merge complete Account JaCoCo coverage - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - name: 📤 Upload Complete Account Coverage Report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 @@ -1441,7 +1441,7 @@ jobs: cache-read-only: false - name: Merge complete Game Session JaCoCo coverage - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - name: 📤 Upload Complete Game Session Coverage Report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index ea2804fecd..29a2214208 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1172,7 +1172,7 @@ jobs: cache-read-only: false - name: Build service JAR - run: ./gradlew :${{ matrix.service }}:bootJar + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 @@ -1414,7 +1414,7 @@ jobs: - name: Build controller JAR and image locally run: | set -euo pipefail - ./gradlew :hosted-environment-identity-controller:bootJar + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ @@ -1898,7 +1898,8 @@ jobs: - name: Build controller image for credential-free local validation run: | set -euo pipefail - ./gradlew :hosted-environment-identity-controller:bootJar + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ + --runner ./gradlew -- :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="$BASE_IMAGE" \ diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index a4bc626f22..f4232fbdeb 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; + const canonicalRuntimeWorkflowSha256 = "b89a1fb4bb324220c842b2250ca82f8db0d5d17b7ef86e70ad56e107ed4bce34"; // Retain the exact fail-red producer still executed by trusted base refreshes. const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index e92de2b824..2d5e2ca1b9 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -109,6 +109,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Generates protobuf outputs to keep generated stubs aligned with the checked-in schemas. - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. +- Gradle-based Validation and runtime builds, including affected-module checks, controller builds and the source-built Compose boot-jar command, can recover one exact pinned Gradle-wrapper distribution HTTP 429, 500, 502, 503 or 504 failure before any Gradle task starts. The recovery uses only the official Gradle GitHub release-asset API for the same stable version, requires the release asset digest and downloaded bytes to match the repository's SHA-256 pin, checks the exact asset size, and atomically seeds the ordinary wrapper cache without replacing existing bytes. Metadata and asset requests have bounded time/size limits. The unchanged wrapper command then retries once and still verifies/extracts its own archive. No alternate Gradle version, mirror, compiler/test retry or successful runtime claim is introduced; missing, inconsistent, custom-layout, mixed, interrupted or unrecognized evidence retains the original failure. - Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. - On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account and Game Session retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 4819030968..efd6554473 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -1044,3 +1044,167 @@ run_case common-web-support 125 assert_no_retry echo "Gradle dependency-recovery contract passed." + + +# The normal module path retries the unchanged invocation once after a verified +# archive recovery. A second wrapper failure remains failed and is not retried. +for retry_result in success failure; do + new_case "distribution-$retry_result" + mkdir -p "$CASE_DIR/gradle/wrapper" + fixture_sha="$(printf '%s' 'controlled pinned distribution archive' | sha256sum | cut -d ' ' -f 1)" + printf '%s\n' 'distributionBase=GRADLE_USER_HOME' 'distributionPath=wrapper/dists' \ + 'zipStoreBase=GRADLE_USER_HOME' 'zipStorePath=wrapper/dists' \ + 'distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip' \ + "distributionSha256Sum=$fixture_sha" > "$CASE_DIR/gradle/wrapper/gradle-wrapper.properties" + cat > "$CASE_DIR/bin/curl" <<'CURL_DISTRIBUTION' +#!/usr/bin/env python3 +import hashlib +import json +from pathlib import Path +import sys +payload = b"controlled pinned distribution archive" +output = Path(sys.argv[sys.argv.index("-o") + 1]) +if sys.argv[-1].endswith("/releases/tags/v9.9.0"): + output.write_text(json.dumps({"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": "sha256:" + hashlib.sha256(payload).hexdigest()}]})) +else: + assert sys.argv[-1] == "https://api.github.com/repos/gradle/gradle-distributions/releases/assets/7" + output.write_bytes(payload) +CURL_DISTRIBUTION + chmod +x "$CASE_DIR/bin/curl" + # shellcheck disable=SC2016 + write_wrapper 'if [[ "$call_count" -eq 1 || "${FAKE_DISTRIBUTION_RETRY_RESULT:-}" == failure ]]; then + echo "Downloading https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" + echo "java.io.IOException: Server returned HTTP response code: 504 for URL: https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" + exit 1 + fi + exit 0' + expected=0 + [[ "$retry_result" == success ]] || expected=1 + GRADLE_USER_HOME="$CASE_DIR/gradle-cache" FAKE_DISTRIBUTION_RETRY_RESULT="$retry_result" run_case common-web-support "$expected" + assert_call_count 2 + [[ "$(sed -n '1p' "$CASE_DIR/calls")" == "$(sed -n '2p' "$CASE_DIR/calls")" ]] || fail "distribution recovery changed the Gradle invocation" + ! grep -Fq -- '--refresh-dependencies' "$CASE_DIR/calls" || fail "distribution transport must not force dependency refresh" + assert_output_contains "Recovered the pinned wrapper distribution before task execution" +done + +# Exercise the wrapper transport recovery separately from Maven metadata refresh. +python3 - "$RECOVERY_RUNNER" <<'PY_DISTRIBUTION_TEST' +import contextlib +import hashlib +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +runner = Path(sys.argv[1]).read_text() +code = runner.split("<<'PY_DISTRIBUTION'\n", 1)[1].split("\nPY_DISTRIBUTION\n", 1)[0] +url = "https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" +payload = b"controlled pinned distribution archive" +checksum = hashlib.sha256(payload).hexdigest() + +class DistributionRecovery(unittest.TestCase): + def attempt(self, *, log=None, changes=None, metadata=None, body=payload, args=(), error=None, existing=None): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + props = { + "distributionBase": "GRADLE_USER_HOME", "distributionPath": "wrapper/dists", + "zipStoreBase": "GRADLE_USER_HOME", "zipStorePath": "wrapper/dists", + "distributionUrl": url.replace(":", "\\:"), "distributionSha256Sum": checksum, + } + props.update(changes or {}) + properties = root / "gradle/wrapper/gradle-wrapper.properties" + properties.parent.mkdir(parents=True) + properties.write_text("".join(f"{key}={value}\n" for key, value in props.items() if value is not None)) + log_path = root / "normal.log" + log_path.write_text(log if log is not None else f'Downloading {url}\nException in thread "main" java.io.IOException: Server returned HTTP response code: 504 for URL: {url}\n') + release = metadata if metadata is not None else {"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": f"sha256:{checksum}"}]} + cache = root / "cache" + number = int.from_bytes(hashlib.md5(url.encode()).digest(), "big") + key = "" + while number: + number, remainder = divmod(number, 36) + key = "0123456789abcdefghijklmnopqrstuvwxyz"[remainder] + key + target = cache / "wrapper/dists/gradle-9.9.0-bin" / key / "gradle-9.9.0-bin.zip" + if existing is not None: + target.parent.mkdir(parents=True) + target.write_bytes(existing) + calls = [] + def fetch(command, **options): + calls.append(command) + self.assertEqual(command[0], "curl") + self.assertTrue(options["check"]) + self.assertLessEqual(options["timeout"], 80) + if error is not None: + raise error + output = Path(command[command.index("-o") + 1]) + if command[-1].endswith("/releases/tags/v9.9.0"): + self.assertIn("Accept: application/vnd.github+json", command) + output.write_text(json.dumps(release)) + else: + self.assertEqual(command[-1], "https://api.github.com/repos/gradle/gradle-distributions/releases/assets/7") + self.assertIn("Accept: application/octet-stream", command) + output.write_bytes(body) + return subprocess.CompletedProcess(command, 0) + with patch.object(sys, "argv", ["recovery", str(root), str(log_path), *args]), patch.dict(os.environ, {"GRADLE_USER_HOME": str(cache)}), patch("subprocess.run", side_effect=fetch), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as outcome: + exec(compile(code, "distribution-recovery", "exec"), {}) + return outcome.exception.code, calls, target.read_bytes() if target.exists() else None + + def test_exact_pinned_distribution_uses_official_api_and_keeps_bytes(self): + status, calls, stored = self.attempt() + self.assertEqual(status, 0) + self.assertEqual(len(calls), 2) + self.assertEqual(stored, payload) + + def test_existing_verified_archive_is_not_replaced(self): + status, calls, stored = self.attempt(existing=payload) + self.assertEqual((status, calls, stored), (0, [], payload)) + status, calls, stored = self.attempt(existing=b"unexpected existing archive") + self.assertEqual((status, calls, stored), (1, [], b"unexpected existing archive")) + + def test_task_test_compile_and_unrecognized_failures_never_fetch(self): + base = f'Downloading {url}\nException in thread "main" java.io.IOException: Server returned HTTP response code: 504 for URL: {url}\n' + for log in ["unrelated failure", base.replace("504", "404"), base.replace(url, url.replace("9.9.0", "9.8.2")), "> Task :account-service:test\n" + base, "\x1b[31m> Task :account-service:test\x1b[0m\n" + base, "Compilation failed\n" + base, "There were failing tests\n" + base, "BUILD FAILED\n" + base, "java.lang.IllegalStateException: unrelated failure\n" + base, base + "Downloading https://untrusted.example/other.zip\n"]: + with self.subTest(log=log): + status, calls, stored = self.attempt(log=log) + self.assertEqual((status, calls, stored), (1, [], None)) + + def test_bad_pin_layout_and_different_cache_args_never_fetch(self): + for changes in [{"distributionSha256Sum": None}, {"distributionSha256Sum": "bad"}, {"distributionUrl": "https://untrusted.example/gradle-9.9.0-bin.zip"}, {"zipStorePath": "other"}, {"distributionBase": "PROJECT"}]: + with self.subTest(changes=changes): + self.assertEqual(self.attempt(changes=changes)[:2], (1, [])) + for args in [("-g", "/other"), ("--gradle-user-home=/other",)]: + self.assertEqual(self.attempt(args=args)[:2], (1, [])) + + def test_malformed_or_mismatched_release_metadata_does_not_download_asset(self): + base = {"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": f"sha256:{checksum}"}]} + variants = [{}, [], {**base, "assets": None}, {**base, "assets": ["malformed"]}, {**base, "tag_name": "v9.8.2"}, {**base, "draft": True}, {**base, "prerelease": True}, {**base, "assets": []}, {**base, "assets": base["assets"] * 2}] + for change in [{"id": True}, {"id": 0}, {"size": 0}, {"size": 536870913}, {"digest": "sha256:" + "0" * 64}]: + variants.append({**base, "assets": [{**base["assets"][0], **change}]}) + for metadata in variants: + with self.subTest(metadata=metadata): + status, calls, stored = self.attempt(metadata=metadata) + self.assertEqual(status, 1) + self.assertEqual(len(calls), 1) + self.assertIsNone(stored) + + def test_download_error_and_checksum_or_size_mismatch_publish_nothing(self): + for body in [payload + b"extra", b"x" * len(payload)]: + status, calls, stored = self.attempt(body=body) + self.assertEqual((status, len(calls), stored), (1, 2, None)) + status, calls, stored = self.attempt(error=subprocess.CalledProcessError(22, "curl")) + self.assertEqual((status, len(calls), stored), (1, 1, None)) + +unittest.main(argv=["distribution-recovery"], exit=True) +PY_DISTRIBUTION_TEST +for workflow in "$ROOT_DIR/.github/workflows/ci.yml" "$ROOT_DIR/.github/workflows/runtime-images.yml"; do + if grep -Eq '^[[:space:]]*(run: )?\./gradlew[[:space:]]' "$workflow"; then + fail "Gradle bootstrap bypasses bounded distribution recovery in $workflow" + fi +done +echo "Official Gradle distribution transport contracts passed" diff --git a/dev-tools/validation/run-gradle-with-dependency-recovery.sh b/dev-tools/validation/run-gradle-with-dependency-recovery.sh index 459f3b528e..0ec3c9611c 100644 --- a/dev-tools/validation/run-gradle-with-dependency-recovery.sh +++ b/dev-tools/validation/run-gradle-with-dependency-recovery.sh @@ -464,6 +464,143 @@ retry_delay_seconds() { printf '%s\n' "$delay" } +# Recover only a wrapper download failure before any Gradle task starts. The +# official API is another transport for the same pinned release bytes, never a +# version fallback or permission to retry compilation/tests. +recover_wrapper_distribution() { + local root_dir + root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + grep -Eq '^Downloading https://services[.]gradle[.]org/distributions/gradle-[0-9]+[.][0-9]+[.][0-9]+-bin[.]zip$' "$NORMAL_LOG" || return 1 + python3 - "$root_dir" "$NORMAL_LOG" "${GRADLE_ARGS[@]}" <<'PY_DISTRIBUTION' +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +root, log = Path(sys.argv[1]), Path(sys.argv[2]) + +def digest(path): + value = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + value.update(chunk) + return value.hexdigest() + +def recover(): + # A different CLI cache selection or custom layout is not this recovery path. + if any(arg == "-g" or arg.startswith("-g") or arg.startswith("--gradle-user-home") for arg in sys.argv[3:]): + return False + if log.stat().st_size > 1048576: + return False + text = log.read_text(errors="replace") + text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text) + if re.search(r"^> Task |BUILD FAILED|Compilation failed|There were failing tests|\berror:", text, re.MULTILINE): + return False + props = {} + properties = root / "gradle/wrapper/gradle-wrapper.properties" + if properties.stat().st_size > 65536: + return False + for line in properties.read_text().splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + key, value = line.split("=", 1) + if key in props: + return False + props[key] = value.replace("\\:", ":") + url = props.get("distributionUrl", "") + match = re.fullmatch(r"https://services\.gradle\.org/distributions/gradle-([0-9]+\.[0-9]+\.[0-9]+)-bin\.zip", url) + checksum = props.get("distributionSha256Sum", "") + if not match or not re.fullmatch(r"[0-9a-f]{64}", checksum): + return False + if any(props.get(key) != value for key, value in { + "distributionBase": "GRADLE_USER_HOME", "distributionPath": "wrapper/dists", + "zipStoreBase": "GRADLE_USER_HOME", "zipStorePath": "wrapper/dists", + }.items()): + return False + failure = re.compile(r'(?:Exception in thread "main" )?java\.io\.IOException: Server returned HTTP response code: (?:429|500|502|503|504) for URL: ' + re.escape(url)) + if not any(failure.fullmatch(line) for line in text.splitlines()): + return False + # Refuse mixed top-level failures and downloads for a different distribution. + for line in text.splitlines(): + if line.startswith("Downloading ") and line != f"Downloading {url}": + return False + if re.match(r'(?:Exception in thread "[^"]+" )?(?:[A-Za-z_$][\w$]*\.)+[A-Za-z_$][\w$]*(?:Exception|Error):', line) and not failure.fullmatch(line): + return False + version = match[1] + name = f"gradle-{version}-bin.zip" + cache_root = Path(os.environ.get("GRADLE_USER_HOME") or Path.home() / ".gradle") + # Match Gradle PathAssembler's URL-derived cache key; SHA-256 verifies bytes. + number = int.from_bytes(hashlib.md5(url.encode()).digest(), "big") + cache_key = "" + while number: + number, remainder = divmod(number, 36) + cache_key = "0123456789abcdefghijklmnopqrstuvwxyz"[remainder] + cache_key + target = cache_root / "wrapper/dists" / name.removesuffix(".zip") / cache_key / name + if target.is_symlink(): + return False + if target.exists(): + return digest(target) == checksum + with tempfile.TemporaryDirectory(prefix="distribution-", dir=log.parent) as temporary: + metadata, archive = Path(temporary) / "release.json", Path(temporary) / name + common = ["curl", "-fsSL", "--retry", "2", "--retry-delay", "2", "--connect-timeout", "10"] + subprocess.run(common + ["--max-time", "20", "--retry-max-time", "25", "--max-filesize", "2097152", + "-H", "Accept: application/vnd.github+json", "-o", str(metadata), + f"https://api.github.com/repos/gradle/gradle-distributions/releases/tags/v{version}"], + check=True, timeout=30) + release = json.loads(metadata.read_text()) + if not isinstance(release, dict) or not isinstance(release.get("assets"), list): + return False + if any(not isinstance(asset, dict) for asset in release["assets"]): + return False + assets = [asset for asset in release["assets"] if asset.get("name") == name] + if release.get("tag_name") != f"v{version}" or release.get("draft") or release.get("prerelease") or len(assets) != 1: + return False + asset = assets[0] + asset_id, size = asset.get("id"), asset.get("size") + if type(asset_id) is not int or asset_id <= 0 or type(size) is not int or not 0 < size <= 536870912: + return False + if asset.get("digest") != f"sha256:{checksum}": + return False + subprocess.run(common + ["--max-time", "60", "--retry-max-time", "70", "--max-filesize", str(size), + "-H", "Accept: application/octet-stream", "-o", str(archive), + f"https://api.github.com/repos/gradle/gradle-distributions/releases/assets/{asset_id}"], + check=True, timeout=80) + if archive.stat().st_size != size or digest(archive) != checksum: + return False + target.parent.mkdir(parents=True, exist_ok=True) + # Publish a complete verified archive atomically without replacing an + # existing archive. The ordinary wrapper still verifies and extracts it. + with tempfile.NamedTemporaryFile(prefix="verified-", dir=target.parent, delete=False) as output: + candidate = Path(output.name) + try: + with archive.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + output.write(chunk) + output.flush() + os.fsync(output.fileno()) + try: + os.link(candidate, target) + except FileExistsError: + if target.is_symlink() or digest(target) != checksum: + return False + finally: + candidate.unlink(missing_ok=True) + print(f"Verified pinned Gradle {version} distribution via official release asset API; SHA256={checksum}.") + return True + +try: + recovered = recover() +except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as failure: + print(f"Pinned Gradle distribution transport recovery unavailable ({type(failure).__name__}); preserving original build failure.", file=sys.stderr) + recovered = False +sys.exit(0 if recovered else 1) +PY_DISTRIBUTION +} + run_gradle_check false "$NORMAL_LOG" if [[ "$GRADLE_EXIT" -eq 0 ]]; then exit 0 @@ -473,6 +610,12 @@ if [[ "$GRADLE_EXIT" -ne 1 ]]; then exit "$GRADLE_EXIT" fi +if recover_wrapper_distribution; then + echo "Recovered the pinned wrapper distribution before task execution; retrying the original Gradle command once." + run_gradle_check false "$REFRESH_LOG" + exit "$GRADLE_EXIT" +fi + if ! is_dependency_resolution_failure "$NORMAL_LOG"; then exit "$GRADLE_EXIT" fi From 32c2736b8551a7c6e6df9810e8437d339faac7d5 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 22:13:47 +1300 Subject: [PATCH 64/66] Align hosted workflow contract with bounded PLAY exception --- ...d-identity-controller-workflow-contract.sh | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 1643550e98..535f7d75c6 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -335,15 +335,30 @@ stop_smoke_step = runtime_steps_by_name["Stop smoke stack"] assert "Build controller image for credential-free local validation" not in runtime_steps_by_name assert "Smoke controller image entrypoint and paused health" not in runtime_steps_by_name assert "if" not in build_runtime_step -assert "if" not in export_step -assert "if" not in upload_step +# A passed job under the bounded PLAY exception must not export images. +# Gate publication on the native smoke outcome, never its continued conclusion. +artifact_gate = ( + "${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' " + "|| steps.runtime-smoke.outcome == 'success') }}" +) +assert export_step["if"] == artifact_gate +assert upload_step["if"] == artifact_gate +assert runtime_steps_by_name["Summarize secure PR runtime artifact"]["if"] == artifact_gate +assert upload_step["id"] == "runtime-artifact" +assert runtime_job["outputs"]["publishable"] == ( + "${{ steps.runtime-artifact.outcome == 'success' }}" +) +assert run_smoke_step["id"] == "runtime-smoke" +assert run_smoke_step["continue-on-error"] is True +assert run_smoke_step["env"]["FIREMUD_SMOKE_ADMISSION_QUALIFICATION"] == "held" smoke_gate = "${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }}" assert setup_smoke_python_step["if"] == smoke_gate assert setup_smoke_python_step["uses"] == "./.github/actions/setup-python" assert setup_smoke_python_step["with"] == {"requirements": "smoke"} assert run_smoke_step["if"] == smoke_gate assert dump_logs_step["if"] == ( - "${{ failure() && needs.image-meta.outputs.runtime_smoke_required == 'true' " + "${{ always() && steps.runtime-smoke.outcome == 'failure' && " + "needs.image-meta.outputs.runtime_smoke_required == 'true' " "&& steps.minio-source.outputs.server_image_id != '' " "&& steps.minio-source.outputs.client_image_id != '' }}" ) @@ -353,6 +368,35 @@ assert stop_smoke_step["if"] == ( "&& steps.minio-source.outputs.client_image_id != '' }}" ) +assert stop_smoke_step["id"] == "runtime-cleanup" +exception_step = runtime_steps_by_name[ + "Known canonical transition PLAY failure with successful authenticated cleanup" +] +assert exception_step["id"] == "canonical-play-transition" +for condition in ( + "always()", + "github.repository == 'benhook1013/FireMUD'", + "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", + "needs.image-meta.outputs.runtime_smoke_required == 'true'", + "steps.runtime-smoke.outcome == 'failure'", + "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", + "steps.runtime-cleanup.outcome == 'success'", +): + assert condition in exception_step["if"], condition +guard = runtime_steps_by_name["Require successful runtime smoke and authenticated cleanup"] +assert guard["if"] == "${{ always() }}" +assert guard["env"] == { + "RUNTIME_SMOKE_REQUIRED": "${{ needs.image-meta.outputs.runtime_smoke_required }}", + "RUNTIME_SMOKE_OUTCOME": "${{ steps.runtime-smoke.outcome }}", + "RUNTIME_CLEANUP_OUTCOME": "${{ steps.runtime-cleanup.outcome }}", + "KNOWN_PLAY_EXCEPTION_OUTCOME": "${{ steps.canonical-play-transition.outcome }}", +} +# Executed success/failure, skipped, cancelled and malformed-outcome guard cases +# are exercised by pr-required-gate-context-contract.sh. +assert "needs.pr-local-smoke.outputs.publishable == 'true'" in ( + workflow["jobs"]["dispatch-pr-runtime-publication"]["if"] +) + controller_job = workflow["jobs"]["pr-controller-smoke"] assert controller_job["needs"] == ["image-meta"] assert "needs.image-meta.outputs.controller_smoke_required == 'true'" in ( From 0630c1038c87253e252528cece01c9cd8208788c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 22:18:53 +1300 Subject: [PATCH 65/66] Place independent wrapper retry tuning in existing successor --- gradle/wrapper/gradle-wrapper.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 910c6f79b7..0bb71f3468 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -2,8 +2,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionSha256Sum=0b00b0ffe07c4d4789c12d4935a44a7057d55774b7540bd4a3f76f336deb177a distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip -networkTimeout=60000 -retries=3 +networkTimeout=10000 +retries=0 retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME From ab637e7559a0831993b55f4de3c4af3c13337c41 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 22:54:28 +1300 Subject: [PATCH 66/66] Keep distribution recovery with the existing CI successor --- .github/workflows/ci.yml | 12 +- .github/workflows/runtime-images.yml | 7 +- .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 1 - .../gradle-dependency-recovery-contract.sh | 164 ------------------ .../run-gradle-with-dependency-recovery.sh | 143 --------------- 6 files changed, 10 insertions(+), 319 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d228afc118..0389908fe9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -250,7 +250,7 @@ jobs: - name: Compile the actual Buf-generated Java sources run: | test -n "$(find protos/gen/java -name '*.java' -print -quit)" - bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- compileBufGeneratedJava + ./gradlew compileBufGeneratedJava docker-lint: name: Dockerfile Lint @@ -681,7 +681,7 @@ jobs: - name: 🧪 Check Flyway Migration Versions env: FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} - run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkFlywayVersions + run: ./gradlew checkFlywayVersions grpc-transport-config-sanity-checks: name: gRPC Transport Configuration Sanity Checks @@ -717,7 +717,7 @@ jobs: cache-read-only: false - name: 🧪 Check gRPC Transport Configuration - run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkGrpcTransportConfig checkGrpcPublicMethods + run: ./gradlew checkGrpcTransportConfig checkGrpcPublicMethods workflow-lint: name: GitHub Workflow Lint @@ -1133,7 +1133,7 @@ jobs: - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) && (matrix.module != 'account-service' && matrix.module != 'game-session-service' || matrix.partition == '1') }} - run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck + run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck - name: 📈 Parse Coverage % id: coverage @@ -1330,7 +1330,7 @@ jobs: cache-read-only: false - name: Merge complete Account JaCoCo coverage - run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes + run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - name: 📤 Upload Complete Account Coverage Report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 @@ -1441,7 +1441,7 @@ jobs: cache-read-only: false - name: Merge complete Game Session JaCoCo coverage - run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes + run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - name: 📤 Upload Complete Game Session Coverage Report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 29a2214208..ea2804fecd 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1172,7 +1172,7 @@ jobs: cache-read-only: false - name: Build service JAR - run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar + run: ./gradlew :${{ matrix.service }}:bootJar - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 @@ -1414,7 +1414,7 @@ jobs: - name: Build controller JAR and image locally run: | set -euo pipefail - bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + ./gradlew :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ @@ -1898,8 +1898,7 @@ jobs: - name: Build controller image for credential-free local validation run: | set -euo pipefail - bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ - --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + ./gradlew :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="$BASE_IMAGE" \ diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index f4232fbdeb..a4bc626f22 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "b89a1fb4bb324220c842b2250ca82f8db0d5d17b7ef86e70ad56e107ed4bce34"; + const canonicalRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; // Retain the exact fail-red producer still executed by trusted base refreshes. const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 2d5e2ca1b9..e92de2b824 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -109,7 +109,6 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Generates protobuf outputs to keep generated stubs aligned with the checked-in schemas. - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. -- Gradle-based Validation and runtime builds, including affected-module checks, controller builds and the source-built Compose boot-jar command, can recover one exact pinned Gradle-wrapper distribution HTTP 429, 500, 502, 503 or 504 failure before any Gradle task starts. The recovery uses only the official Gradle GitHub release-asset API for the same stable version, requires the release asset digest and downloaded bytes to match the repository's SHA-256 pin, checks the exact asset size, and atomically seeds the ordinary wrapper cache without replacing existing bytes. Metadata and asset requests have bounded time/size limits. The unchanged wrapper command then retries once and still verifies/extracts its own archive. No alternate Gradle version, mirror, compiler/test retry or successful runtime claim is introduced; missing, inconsistent, custom-layout, mixed, interrupted or unrecognized evidence retains the original failure. - Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. - On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account and Game Session retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index efd6554473..4819030968 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -1044,167 +1044,3 @@ run_case common-web-support 125 assert_no_retry echo "Gradle dependency-recovery contract passed." - - -# The normal module path retries the unchanged invocation once after a verified -# archive recovery. A second wrapper failure remains failed and is not retried. -for retry_result in success failure; do - new_case "distribution-$retry_result" - mkdir -p "$CASE_DIR/gradle/wrapper" - fixture_sha="$(printf '%s' 'controlled pinned distribution archive' | sha256sum | cut -d ' ' -f 1)" - printf '%s\n' 'distributionBase=GRADLE_USER_HOME' 'distributionPath=wrapper/dists' \ - 'zipStoreBase=GRADLE_USER_HOME' 'zipStorePath=wrapper/dists' \ - 'distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip' \ - "distributionSha256Sum=$fixture_sha" > "$CASE_DIR/gradle/wrapper/gradle-wrapper.properties" - cat > "$CASE_DIR/bin/curl" <<'CURL_DISTRIBUTION' -#!/usr/bin/env python3 -import hashlib -import json -from pathlib import Path -import sys -payload = b"controlled pinned distribution archive" -output = Path(sys.argv[sys.argv.index("-o") + 1]) -if sys.argv[-1].endswith("/releases/tags/v9.9.0"): - output.write_text(json.dumps({"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": "sha256:" + hashlib.sha256(payload).hexdigest()}]})) -else: - assert sys.argv[-1] == "https://api.github.com/repos/gradle/gradle-distributions/releases/assets/7" - output.write_bytes(payload) -CURL_DISTRIBUTION - chmod +x "$CASE_DIR/bin/curl" - # shellcheck disable=SC2016 - write_wrapper 'if [[ "$call_count" -eq 1 || "${FAKE_DISTRIBUTION_RETRY_RESULT:-}" == failure ]]; then - echo "Downloading https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" - echo "java.io.IOException: Server returned HTTP response code: 504 for URL: https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" - exit 1 - fi - exit 0' - expected=0 - [[ "$retry_result" == success ]] || expected=1 - GRADLE_USER_HOME="$CASE_DIR/gradle-cache" FAKE_DISTRIBUTION_RETRY_RESULT="$retry_result" run_case common-web-support "$expected" - assert_call_count 2 - [[ "$(sed -n '1p' "$CASE_DIR/calls")" == "$(sed -n '2p' "$CASE_DIR/calls")" ]] || fail "distribution recovery changed the Gradle invocation" - ! grep -Fq -- '--refresh-dependencies' "$CASE_DIR/calls" || fail "distribution transport must not force dependency refresh" - assert_output_contains "Recovered the pinned wrapper distribution before task execution" -done - -# Exercise the wrapper transport recovery separately from Maven metadata refresh. -python3 - "$RECOVERY_RUNNER" <<'PY_DISTRIBUTION_TEST' -import contextlib -import hashlib -import io -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -runner = Path(sys.argv[1]).read_text() -code = runner.split("<<'PY_DISTRIBUTION'\n", 1)[1].split("\nPY_DISTRIBUTION\n", 1)[0] -url = "https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" -payload = b"controlled pinned distribution archive" -checksum = hashlib.sha256(payload).hexdigest() - -class DistributionRecovery(unittest.TestCase): - def attempt(self, *, log=None, changes=None, metadata=None, body=payload, args=(), error=None, existing=None): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - props = { - "distributionBase": "GRADLE_USER_HOME", "distributionPath": "wrapper/dists", - "zipStoreBase": "GRADLE_USER_HOME", "zipStorePath": "wrapper/dists", - "distributionUrl": url.replace(":", "\\:"), "distributionSha256Sum": checksum, - } - props.update(changes or {}) - properties = root / "gradle/wrapper/gradle-wrapper.properties" - properties.parent.mkdir(parents=True) - properties.write_text("".join(f"{key}={value}\n" for key, value in props.items() if value is not None)) - log_path = root / "normal.log" - log_path.write_text(log if log is not None else f'Downloading {url}\nException in thread "main" java.io.IOException: Server returned HTTP response code: 504 for URL: {url}\n') - release = metadata if metadata is not None else {"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": f"sha256:{checksum}"}]} - cache = root / "cache" - number = int.from_bytes(hashlib.md5(url.encode()).digest(), "big") - key = "" - while number: - number, remainder = divmod(number, 36) - key = "0123456789abcdefghijklmnopqrstuvwxyz"[remainder] + key - target = cache / "wrapper/dists/gradle-9.9.0-bin" / key / "gradle-9.9.0-bin.zip" - if existing is not None: - target.parent.mkdir(parents=True) - target.write_bytes(existing) - calls = [] - def fetch(command, **options): - calls.append(command) - self.assertEqual(command[0], "curl") - self.assertTrue(options["check"]) - self.assertLessEqual(options["timeout"], 80) - if error is not None: - raise error - output = Path(command[command.index("-o") + 1]) - if command[-1].endswith("/releases/tags/v9.9.0"): - self.assertIn("Accept: application/vnd.github+json", command) - output.write_text(json.dumps(release)) - else: - self.assertEqual(command[-1], "https://api.github.com/repos/gradle/gradle-distributions/releases/assets/7") - self.assertIn("Accept: application/octet-stream", command) - output.write_bytes(body) - return subprocess.CompletedProcess(command, 0) - with patch.object(sys, "argv", ["recovery", str(root), str(log_path), *args]), patch.dict(os.environ, {"GRADLE_USER_HOME": str(cache)}), patch("subprocess.run", side_effect=fetch), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as outcome: - exec(compile(code, "distribution-recovery", "exec"), {}) - return outcome.exception.code, calls, target.read_bytes() if target.exists() else None - - def test_exact_pinned_distribution_uses_official_api_and_keeps_bytes(self): - status, calls, stored = self.attempt() - self.assertEqual(status, 0) - self.assertEqual(len(calls), 2) - self.assertEqual(stored, payload) - - def test_existing_verified_archive_is_not_replaced(self): - status, calls, stored = self.attempt(existing=payload) - self.assertEqual((status, calls, stored), (0, [], payload)) - status, calls, stored = self.attempt(existing=b"unexpected existing archive") - self.assertEqual((status, calls, stored), (1, [], b"unexpected existing archive")) - - def test_task_test_compile_and_unrecognized_failures_never_fetch(self): - base = f'Downloading {url}\nException in thread "main" java.io.IOException: Server returned HTTP response code: 504 for URL: {url}\n' - for log in ["unrelated failure", base.replace("504", "404"), base.replace(url, url.replace("9.9.0", "9.8.2")), "> Task :account-service:test\n" + base, "\x1b[31m> Task :account-service:test\x1b[0m\n" + base, "Compilation failed\n" + base, "There were failing tests\n" + base, "BUILD FAILED\n" + base, "java.lang.IllegalStateException: unrelated failure\n" + base, base + "Downloading https://untrusted.example/other.zip\n"]: - with self.subTest(log=log): - status, calls, stored = self.attempt(log=log) - self.assertEqual((status, calls, stored), (1, [], None)) - - def test_bad_pin_layout_and_different_cache_args_never_fetch(self): - for changes in [{"distributionSha256Sum": None}, {"distributionSha256Sum": "bad"}, {"distributionUrl": "https://untrusted.example/gradle-9.9.0-bin.zip"}, {"zipStorePath": "other"}, {"distributionBase": "PROJECT"}]: - with self.subTest(changes=changes): - self.assertEqual(self.attempt(changes=changes)[:2], (1, [])) - for args in [("-g", "/other"), ("--gradle-user-home=/other",)]: - self.assertEqual(self.attempt(args=args)[:2], (1, [])) - - def test_malformed_or_mismatched_release_metadata_does_not_download_asset(self): - base = {"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": f"sha256:{checksum}"}]} - variants = [{}, [], {**base, "assets": None}, {**base, "assets": ["malformed"]}, {**base, "tag_name": "v9.8.2"}, {**base, "draft": True}, {**base, "prerelease": True}, {**base, "assets": []}, {**base, "assets": base["assets"] * 2}] - for change in [{"id": True}, {"id": 0}, {"size": 0}, {"size": 536870913}, {"digest": "sha256:" + "0" * 64}]: - variants.append({**base, "assets": [{**base["assets"][0], **change}]}) - for metadata in variants: - with self.subTest(metadata=metadata): - status, calls, stored = self.attempt(metadata=metadata) - self.assertEqual(status, 1) - self.assertEqual(len(calls), 1) - self.assertIsNone(stored) - - def test_download_error_and_checksum_or_size_mismatch_publish_nothing(self): - for body in [payload + b"extra", b"x" * len(payload)]: - status, calls, stored = self.attempt(body=body) - self.assertEqual((status, len(calls), stored), (1, 2, None)) - status, calls, stored = self.attempt(error=subprocess.CalledProcessError(22, "curl")) - self.assertEqual((status, len(calls), stored), (1, 1, None)) - -unittest.main(argv=["distribution-recovery"], exit=True) -PY_DISTRIBUTION_TEST -for workflow in "$ROOT_DIR/.github/workflows/ci.yml" "$ROOT_DIR/.github/workflows/runtime-images.yml"; do - if grep -Eq '^[[:space:]]*(run: )?\./gradlew[[:space:]]' "$workflow"; then - fail "Gradle bootstrap bypasses bounded distribution recovery in $workflow" - fi -done -echo "Official Gradle distribution transport contracts passed" diff --git a/dev-tools/validation/run-gradle-with-dependency-recovery.sh b/dev-tools/validation/run-gradle-with-dependency-recovery.sh index 0ec3c9611c..459f3b528e 100644 --- a/dev-tools/validation/run-gradle-with-dependency-recovery.sh +++ b/dev-tools/validation/run-gradle-with-dependency-recovery.sh @@ -464,143 +464,6 @@ retry_delay_seconds() { printf '%s\n' "$delay" } -# Recover only a wrapper download failure before any Gradle task starts. The -# official API is another transport for the same pinned release bytes, never a -# version fallback or permission to retry compilation/tests. -recover_wrapper_distribution() { - local root_dir - root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" - grep -Eq '^Downloading https://services[.]gradle[.]org/distributions/gradle-[0-9]+[.][0-9]+[.][0-9]+-bin[.]zip$' "$NORMAL_LOG" || return 1 - python3 - "$root_dir" "$NORMAL_LOG" "${GRADLE_ARGS[@]}" <<'PY_DISTRIBUTION' -import hashlib -import json -import os -from pathlib import Path -import re -import subprocess -import sys -import tempfile - -root, log = Path(sys.argv[1]), Path(sys.argv[2]) - -def digest(path): - value = hashlib.sha256() - with path.open("rb") as source: - for chunk in iter(lambda: source.read(1024 * 1024), b""): - value.update(chunk) - return value.hexdigest() - -def recover(): - # A different CLI cache selection or custom layout is not this recovery path. - if any(arg == "-g" or arg.startswith("-g") or arg.startswith("--gradle-user-home") for arg in sys.argv[3:]): - return False - if log.stat().st_size > 1048576: - return False - text = log.read_text(errors="replace") - text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text) - if re.search(r"^> Task |BUILD FAILED|Compilation failed|There were failing tests|\berror:", text, re.MULTILINE): - return False - props = {} - properties = root / "gradle/wrapper/gradle-wrapper.properties" - if properties.stat().st_size > 65536: - return False - for line in properties.read_text().splitlines(): - if not line.strip() or line.lstrip().startswith("#"): - continue - key, value = line.split("=", 1) - if key in props: - return False - props[key] = value.replace("\\:", ":") - url = props.get("distributionUrl", "") - match = re.fullmatch(r"https://services\.gradle\.org/distributions/gradle-([0-9]+\.[0-9]+\.[0-9]+)-bin\.zip", url) - checksum = props.get("distributionSha256Sum", "") - if not match or not re.fullmatch(r"[0-9a-f]{64}", checksum): - return False - if any(props.get(key) != value for key, value in { - "distributionBase": "GRADLE_USER_HOME", "distributionPath": "wrapper/dists", - "zipStoreBase": "GRADLE_USER_HOME", "zipStorePath": "wrapper/dists", - }.items()): - return False - failure = re.compile(r'(?:Exception in thread "main" )?java\.io\.IOException: Server returned HTTP response code: (?:429|500|502|503|504) for URL: ' + re.escape(url)) - if not any(failure.fullmatch(line) for line in text.splitlines()): - return False - # Refuse mixed top-level failures and downloads for a different distribution. - for line in text.splitlines(): - if line.startswith("Downloading ") and line != f"Downloading {url}": - return False - if re.match(r'(?:Exception in thread "[^"]+" )?(?:[A-Za-z_$][\w$]*\.)+[A-Za-z_$][\w$]*(?:Exception|Error):', line) and not failure.fullmatch(line): - return False - version = match[1] - name = f"gradle-{version}-bin.zip" - cache_root = Path(os.environ.get("GRADLE_USER_HOME") or Path.home() / ".gradle") - # Match Gradle PathAssembler's URL-derived cache key; SHA-256 verifies bytes. - number = int.from_bytes(hashlib.md5(url.encode()).digest(), "big") - cache_key = "" - while number: - number, remainder = divmod(number, 36) - cache_key = "0123456789abcdefghijklmnopqrstuvwxyz"[remainder] + cache_key - target = cache_root / "wrapper/dists" / name.removesuffix(".zip") / cache_key / name - if target.is_symlink(): - return False - if target.exists(): - return digest(target) == checksum - with tempfile.TemporaryDirectory(prefix="distribution-", dir=log.parent) as temporary: - metadata, archive = Path(temporary) / "release.json", Path(temporary) / name - common = ["curl", "-fsSL", "--retry", "2", "--retry-delay", "2", "--connect-timeout", "10"] - subprocess.run(common + ["--max-time", "20", "--retry-max-time", "25", "--max-filesize", "2097152", - "-H", "Accept: application/vnd.github+json", "-o", str(metadata), - f"https://api.github.com/repos/gradle/gradle-distributions/releases/tags/v{version}"], - check=True, timeout=30) - release = json.loads(metadata.read_text()) - if not isinstance(release, dict) or not isinstance(release.get("assets"), list): - return False - if any(not isinstance(asset, dict) for asset in release["assets"]): - return False - assets = [asset for asset in release["assets"] if asset.get("name") == name] - if release.get("tag_name") != f"v{version}" or release.get("draft") or release.get("prerelease") or len(assets) != 1: - return False - asset = assets[0] - asset_id, size = asset.get("id"), asset.get("size") - if type(asset_id) is not int or asset_id <= 0 or type(size) is not int or not 0 < size <= 536870912: - return False - if asset.get("digest") != f"sha256:{checksum}": - return False - subprocess.run(common + ["--max-time", "60", "--retry-max-time", "70", "--max-filesize", str(size), - "-H", "Accept: application/octet-stream", "-o", str(archive), - f"https://api.github.com/repos/gradle/gradle-distributions/releases/assets/{asset_id}"], - check=True, timeout=80) - if archive.stat().st_size != size or digest(archive) != checksum: - return False - target.parent.mkdir(parents=True, exist_ok=True) - # Publish a complete verified archive atomically without replacing an - # existing archive. The ordinary wrapper still verifies and extracts it. - with tempfile.NamedTemporaryFile(prefix="verified-", dir=target.parent, delete=False) as output: - candidate = Path(output.name) - try: - with archive.open("rb") as source: - for chunk in iter(lambda: source.read(1024 * 1024), b""): - output.write(chunk) - output.flush() - os.fsync(output.fileno()) - try: - os.link(candidate, target) - except FileExistsError: - if target.is_symlink() or digest(target) != checksum: - return False - finally: - candidate.unlink(missing_ok=True) - print(f"Verified pinned Gradle {version} distribution via official release asset API; SHA256={checksum}.") - return True - -try: - recovered = recover() -except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as failure: - print(f"Pinned Gradle distribution transport recovery unavailable ({type(failure).__name__}); preserving original build failure.", file=sys.stderr) - recovered = False -sys.exit(0 if recovered else 1) -PY_DISTRIBUTION -} - run_gradle_check false "$NORMAL_LOG" if [[ "$GRADLE_EXIT" -eq 0 ]]; then exit 0 @@ -610,12 +473,6 @@ if [[ "$GRADLE_EXIT" -ne 1 ]]; then exit "$GRADLE_EXIT" fi -if recover_wrapper_distribution; then - echo "Recovered the pinned wrapper distribution before task execution; retrying the original Gradle command once." - run_gradle_check false "$REFRESH_LOG" - exit "$GRADLE_EXIT" -fi - if ! is_dependency_resolution_failure "$NORMAL_LOG"; then exit "$GRADLE_EXIT" fi