diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 5f27e41f6a..693b9bfd6a 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -126,7 +126,7 @@ jobs: echo "::error title=Missing preview head SHA::Manual preview dispatches must supply the current PR head SHA." >&2 exit 1 fi - if [[ "$HEAD_SHA" != "${HEAD_SHA,,}" ]]; then + if [[ ! "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]; then echo "::error title=Noncanonical preview head SHA::Expected lowercase hexadecimal input." >&2 exit 1 fi diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 301928afb1..e240d5d39a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -127,6 +127,8 @@ Fresh-enrollment certification is internal Account owner work, not a public regi The public bootstrap WORLDS source is prepared as an unregistered Account owner and is not yet wired into the existing `ListBootstrapWorlds` facade. Its current schema-backed source is the canonical Account DEMO entitlement; paid-hosting discovery remains unavailable until the subscription schema and retained facade consumers migrate together. Current source and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). +Additional unregistered source prepares separate World Management [`TENANT_OPERATION` entitlement reads](#private-tenant-operation-entitlement-read) and Game Session [player-admission entitlement reads](#private-player-admission-entitlement-read), held hosting provisioning and terminal-resolution owners, a signed canonical V2 scope reader, and an Account client for Entity-owned persisted bootstrap-roster discovery. These sources do not replace the existing public discovery/JOIN facade or runtime entitlement RPC, register a receiver, or enable player admission. The scope reader verifies an existing selector rather than authenticating its caller; the roster read supplies transient persisted discovery rather than a selection, actor allocation, session, or admission result. Exact source boundaries and pending proof are recorded in [local source-foundation preparation](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). + The opaque `bootstrap-connect-scope` artifact uses canonical non-nil Account UUID subject/claim equality. Both browser discovery and the existing direct-text Account producer obtain that identity from Account persistence; the dedicated reader resolves it back to Account-local storage before existing binding checks. Numeric scopes have no compatibility parser: clients obtain fresh scope evidence through bounded rediscovery, while retained rows/receipts are not rewritten and existing retained-replay guards remain. Caller authentication, public-join policy and the held connect-token issuer are unchanged. Detailed receiving proof belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact). 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. @@ -245,6 +247,22 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. +### Private tenant-operation entitlement read + +`AccountTenantOperationEntitlementReadService/ReadTenantOperationEntitlement` is a distinct private `TENANT_OPERATION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/tenant_operation_entitlement_read.proto). Only the exact same-namespace World Management workload may call it over mTLS; method authorization precedes request decoding, and bearer tokens, ambient caller context and caller-supplied workload values cannot replace transport identity. Account derives the evidence's `callerWorkload` from the authenticated peer, never request data. + +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). + +### Private player-admission entitlement read + +`AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The credential is disclosed only to the verified Account peer on this method and must never be logged or persisted as request evidence. + +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). + ### Runtime account identity owner read `RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity` reads Account's already-persisted canonical UUID and provenance for Account's own row. The protobuf in [`runtime_account_identity_service.proto`](../../../../protos/account/v1/runtime_account_identity_service.proto) is the wire authority; Account does not derive an identity from another owner's key or row. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5a56bdc50a..29dbc4cdc1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,10 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The local source-foundation preparation retains the existing numeric subscription schema, runtime reader, public facade and demo seeder. It does not install the V1028-and-later subscription UUID transition, archive numeric subscription rows, retire their reader, or replace the facade with denial stubs. This retained runtime is implementation drift under the canonical [membership and entitlement authority](#membership-and-entitlement-authority), not a second target authority. Schema retirement and a functioning canonical UUID admission replacement remain one downstream receiving boundary; this preparation adds no numeric bridge or dual-authority path. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation) owns source and proof status. + +The manually composed hosting provisioning and terminal-resolution sources require the downstream canonical subscription schema and cannot establish paid lifecycle or entitlement operation against the retained numeric schema. Separate `TENANT_OPERATION` and `PLAYER_ADMISSION` sources/transports, the V2 scope reader, and Account-to-Entity bootstrap-roster client remain unregistered and non-admitting. The player-admission owner performs JWT/registry, provider and protected target reads outside SQL, then rereads current Account issuance, membership, exact retained scope and selected billing source in a final writable `SERIALIZABLE` transaction; failed commit releases no evidence. Its DEMO proof sources use the existing schema, while paid execution requires canonical subscription storage and genuine provider receipts. Existing JOIN transactions are also explicitly writable and `SERIALIZABLE`; neither local guarantee supplies distributed target protection or completes the canonical JOIN commit gate. The [private player-admission API](./api-contracts.md#private-player-admission-entitlement-read) owns the protocol, [Subscription Management](./subscription-management.md) owns billing lifecycle, and the [tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation) owns source/proof limits. + Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This scope-artifact transition itself adds no Game Session text dispatch; the separately qualified ordinary receiving cohort now carries UUID Account identity through the direct-text caller context and Account-to-Entity references. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact) and [ordinary UUID receiving](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). JOIN keeps numeric owner keys inside its retained scope, operation, membership and digest records. A private in-process outcome is projected through full Account owner readback only after the JOIN transaction returns, so response identity failure cannot undo a committed receipt or replace its original outcome. Profile repositories embed only partial Account rows; GET/UPDATE response projection rereads the full owner and supplies its verified UUID to the generated mapper. Both existing export paths verify their already-loaded Account once and reuse that UUID while retaining each profile owner, tenant and mapped-output check. The response identity contract is owned by [Account API contracts](./api-contracts.md); implementation and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-owned-response-uuid-projection). diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 5dd85c3b74..569acfa1af 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`, unavailable owner or storage reads are `UNAVAILABLE`, and invalid stored projections or server response-validation failures are `INTERNAL`; 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/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 489962950c..d86e71ac01 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#player-admission-entitlement-source-preparation). + 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). @@ -64,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 [canonical realm-catalog contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) requires exactly one visible, player-addressable `publicProduction=true` realm per tenant. This collection therefore contains at most one target per canonical tenant and tenant slug; duplicate tenant authority is invalid and refuses the complete collection rather than selecting or grouping a fallback. Other realms returned by realm-listing APIs do not create additional public-production targets. Valid `PLAYER_CREATED` targets are excluded from both discovery reads only after validating their authority and collection uniqueness; malformed or duplicate authority still refuses the complete collection. +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 realm-catalog contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) requires exactly one visible, player-addressable `publicProduction=true` realm per tenant. This collection therefore contains at most one target per canonical tenant and tenant slug; duplicate tenant identities/slugs or realm identities refuse the complete collection rather than selecting or grouping a fallback. Other realms returned by realm-listing APIs do not create additional public-production targets. Malformed or duplicate authority, including `PLAYER_CREATED` authority, 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/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 6b8e888f4c..d8dec13426 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 @@ -235,6 +235,12 @@ Current receiving R1128 passes all 32 selected native executions: 22 Entity crea - Inventory query and mutation proof covers hidden implementation-owned inventory containers, room-ground containers, equipment bindings, basic query filtering, successful audited transfers, failed transfers with no committed audit row, and deterministic retry correlation. - Current parcel documentation proof (parcel-scope run confirmed on 2026-08-20 Pacific/Auckland (2026-08-20 UTC)): `./gradlew linkCheck lintMarkdown` passed with 5,324 total links (5,286 OK, 38 excluded, 0 errors) and 480 Markdown files (0 issues); `bash dev-tools/tests/architecture-doc-contracts.sh` passed 184 tests; and `git diff --check` passed. Runtime/smoke proof is not applicable because this parcel changes documentation only. +### Account bootstrap persisted discovery proof + +Focused [Account client](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), [Entity peer interceptor](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java), [Entity read service](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java), and [persisted repository](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java) tests cover typed client/codec/adapter composition, exact workload/context refusal, closure and bounds, unsupported scope/policy, unavailable source and source-digest drift across SQL. The combined [PostgreSQL/socket-mTLS test source](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java) additionally covers actual Entity/Saga migrations and assignment writer, persisted zero/one actor reads, same-row nonzero and zero levels, account/namespace isolation, quarantine exclusion and unchanged actor/selection/snapshot/retention storage. 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 coverage only. This proof does not establish a complete upstream chain, production registration, Account consumer settlement, private/player-created/auto-provisioned discovery, admission or activation. + +On 2026-11-07, the historical local correction based on source parent `ab249aa4f93929fbdf2ccc8bc7c8aa3cacc2d70c` passed all 20 cases in the four focused suites linked above: nine Account client, three Entity peer-interceptor, five Entity read-service and three Entity repository cases, with zero failures, errors or skips. The gate used `bash dev-tools/validation/run-locked-gradle.sh`, `:account-service:test` and `:entity-management-service:test` with those class-name filters and `--offline -PfullCheck --max-workers=1`. The combined PostgreSQL/socket-mTLS suite was not executed in this local correction because Docker is unavailable; no physical database execution is claimed. The current source adds two Entity receiver cases for malformed requests and stored projection/response-validation classification, bringing the four-suite source inventory to 22 cases (nine Account client, three Entity peer-interceptor, seven Entity read-service and three Entity repository cases). The consolidated correction gate on 2026-11-07 freshly executed all 22 cases with zero failures, errors or skips using the same class filters and canonical Gradle wrapper. The combined PostgreSQL/socket-mTLS suite remains unrun locally. + ### Canonical sealed-roster proof history These paragraphs retain their chronological source/checkpoint attribution. Earlier preparation and run results do not replace the current capability summary or qualify later corrections. @@ -312,3 +318,7 @@ 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 proof and remaining limits are recorded in [Validation and Proof](#account-bootstrap-persisted-discovery-proof). 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 9d0c58965d..d4e6960bbe 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,30 @@ 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. +### Local source-foundation preparation + +The local reconstruction based on `6b86f46f3fd0a76729b27f99b1e573bbac649838` carries selected source from #3389, #3390 and #3403 without their subscription-schema retirement or canonical public-facade cutover. The existing numeric subscription schema, reader, public facade and demo seeder remain unchanged. The only retained [`AccountServiceImpl`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) change makes its independent JOIN transactions explicitly writable and `SERIALIZABLE`; this is local transaction hardening, not completion of the canonical distributed commit gate. Existing runtime behavior remains implementation drift rather than the target contract. + +The #3389 source includes the private [`TENANT_OPERATION` proto](../../../protos/account/v1/tenant_operation_entitlement_read.proto), [strict common evidence codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java), [Account source owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java), [workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java), [gRPC receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java), and [World client](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java). They prepare an explicit paid-or-DEMO eligibility read for the exact same-namespace World workload without source fallback, capacity commitment or player admission. They remain manually composed and unregistered; the paid branch still depends on the missing canonical subscription schema. The [controlled mTLS transport test source](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java) uses a controlled Account source owner and does not establish physical paid entitlement authority. + +Held hosting sources here include the [lifecycle repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java) and [same-owner terminal-resolution composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java), with their focused unit sources. Retained dispatch/readback and fresh Account primary-authentication guards do not enable `CreateSubscription`, a provider worker, cancellation recovery, or a production billing route. Their required canonical intent, provisioning, lifecycle, dispatch and terminal-resolution storage is not installed in this candidate; the dependent physical billing/retention proofs are not carried as candidate qualification. + +Initial provider creation is carried by [#3390](https://github.com/benhook1013/FireMUD/pull/3390), alongside its canonical storage and dispatch physical proof. The [Stripe provisioner](https://github.com/benhook1013/FireMUD/blob/d327e67c51637592637b6a349e59aa74aaf74f55/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java), [provisioning composition](https://github.com/benhook1013/FireMUD/blob/d327e67c51637592637b6a349e59aa74aaf74f55/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java) and both focused unit suites are absent from this front boundary and preserved in that receiver. The paid first-invoice confirmation finding remains open there: `default_incomplete` creation and subscription polling do not complete payment, and controlled active-subscription inputs are not paid-checkout proof. Account/provider-hosted checkout completion after confirmed provider linkage and its proof remain required under [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). This ownership transfer enables no provider worker, runtime registration, automatic charging or activation. + +The #3390 source adds the unregistered [Entity bootstrap-roster proto](../../../protos/entity-management/v1/account_bootstrap_roster_read.proto), [Entity persisted reader](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java), [Account client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java), and [signed V2 scope reader](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java). Discovery is bounded to independently current public-production `SHARED`/`PRESEEDED_ONLY` targets and actual persisted eligible actors, including their stored level and valid empty rosters; it creates no selection, actor, retained roster, session or admission authority. Target reads surrounding Entity SQL detect source movement but supply no distributed hold. The scope reader compares the signed selector with retained Account evidence and requires an externally authenticated Account identity. Neither reader is consumed by the existing public facade. [`CanonicalJoinScopeV2`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java) also redacts its bearer scope in `toString()`. + +Focused unit and controlled physical proof sources are retained, including the [Entity PostgreSQL/mTLS roster tests](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java), [Account roster-client mTLS tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), and [V2 scope-reader units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java). Before the provider-write source transfer, the expanded candidate passed 523 selected cases: 403 Account, eight Entity, 73 Game Session, fourteen Common Platform Core, 21 Common Security and four World client mTLS cases, with no failures, errors or skips. The first expanded run passed 524 cases plus affected integration/cross-service source compilation in 13m16s; removing the previously adjudicated duplicate membership test preserved its richer proof, and the final Account rerun plus affected enabled Checkstyle, SpotBugs, formatting and documentation checks passed in 9m26s. Those historical units and controlled transports do not qualify the reduced boundary or establish physical PostgreSQL or source-built runtime Smoke. After the transfer, affected production/unit/integration compilation, all 51 selected Account owner/handler/lifecycle/workload-guard cases, and enabled Account Checkstyle, SpotBugs and Java formatting pass. Physical integration execution is unrun locally; exact-comparison CI and positive Smoke remain required before this earlier boundary is ready. + +The V1028-and-later subscription UUID transition, immutable retained archive, numeric-authority retirement, production denial stubs, canonical public facade and live `PLAYER_ADMISSION` integration are outside this preparation. Schema retirement and a functioning canonical UUID admission replacement must arrive together at one downstream receiving boundary, preserving retained-data safety without a new numeric bridge or dual authority. No entitlement-receiver registration, production custody, canonical player admission, activation or physical proof success is claimed, and the capability ratings below remain unchanged. + +### Player-admission entitlement source preparation + +The local candidate now retains the [Account player-admission owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java), [exact workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java), [receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java), and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java), with closed protocol/codec and unit/mTLS proof sources. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md#private-player-admission-entitlement-read) owns the wire and caller restrictions. These are manually composed, unregistered components; the default `PLAY` chain still uses the existing numeric entitlement call. No live LOGIN private-result custody, first-party/direct-text scope receiving chain, final admission or `PLAY` wiring is supplied. Policy-aware WORLDS discovery does not widen this read beyond public-production `SHARED`/`PRESEEDED_ONLY` targets. + +Three Account physical proof sources are present: the [current-source PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java), [entitlement-owner PostgreSQL/mTLS suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), and [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java). They prepare DEMO, absent/joined membership, exact scope and committed LOGIN checks on the existing schema; shared owner/context fixture and resource integration must preserve the existing constructors and numeric runtime dependencies. The owner suite controls caller/current issuance and protected Game Session/World inputs; the committed-LOGIN case replaces Account caller doubles with actual committed issuance and recovery while retaining controlled signing, initial delivery and protected targets. None establishes paid billing composition. The four-file World/shared positive composition cohort remains downstream because it requires the canonical UUID direct-text scope DTOs and producer; genuine LOGIN/World positive composition remains an explicit receiving obligation, not dropped scope. + +Historical #3390 proof324 (22 owner and five shared cases), proof335 (three Account PostgreSQL cases) and proof352 (34 client mTLS cases) remain donor-source results. Earlier locally skipped physical aggregates remain skipped; none of these results qualifies this expanded reconstruction. The selected unit/mTLS, affected source compilation and enabled static checks recorded in the foundation proof above retain their pre-transfer comparison; physical execution remains outstanding here. Production mTLS/custody and Redis qualification, complete authenticated target provenance, a World hold through later commitment, paid schema/provider composition, runtime registration and functional admission remain open; point-in-time evidence is not a capacity or admission decision. + ### 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). @@ -30,11 +54,11 @@ Paid-provider observation remains an activation blocker owned by Account billing The current SDK transport uses socket timeouts while consuming the complete response; the [current-read fence](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java) carries no retained policy budget, and the discovery owner has no provider-latency/429 instrumentation or fleet-wide provider-rate qualification. Before paid facade registration, the owners must complete the linked deadline, retained-policy, load and telemetry gates and their physical proof in the canonical subscription receiver. That receiver's missing V1028–V1032 schema and the unregistered runtime composition leave the complete boundary unqualified here. No cache or registration is supplied. This handoff preserves an open implementation obligation; it does not classify the socket-timeout change as a completed activation fix. -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 now prepares the complete visible public-production `SHARED` collection for both `PRESEEDED_ONLY` and `PLAYER_CREATED`. It preserves complete canonical identity/namespace checks, committed owner/no-abort evidence, tenant UUID/slug and realm uniqueness, bounded closed frames and two complete reads with whole-set equality. Strict target selection, roster and admission remain `PRESEEDED_ONLY`. The owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Focused mixed-policy proof sources are `AccountPublicBootstrapWorldsOwnerTest.mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery` and `CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads`; `CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.discoveryCarriesBothSupportedPublicCreationPoliciesWithoutChangingTargetEvidence` separately covers each supported policy. The CLI12 focused receiving run passes these named cases among 194 selected cases (102 Account, 74 Game Session and 18 Common Security), with no failures, errors or skips; the historical 523-case foundation run is not attributed as their proof. Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. -Current component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../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). The latest affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. +Earlier component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../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). The prior affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures, not the local mixed-policy addition. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. -The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof remains component-only. This scope owner is not consumed by the existing facade, and this source slice adds no browser scope reader. Unregistered hosting observer, intent, lifecycle and plan implementations and focused units are present; they do not establish paid discovery against this source slice’s legacy schema: V1028 must archive the old subscription table, V1029 creates the canonical UUID table, and dependent V1030/V1032 plus the facade and its positive consumers remain unimplemented in this source slice. No numeric fallback or second subscription table is introduced. Private `REALMS`, browser/direct scope reading, `PLAYER_ADMISSION`, JOIN consumer migration, default registration and gameplay admission remain separate gaps. +The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof remains component-only. That scope owner and the newly retained [V2 reader](#local-source-foundation-preparation) are not consumed by the existing facade. Unregistered hosting observer, intent, lifecycle and plan implementations and focused units are present; they do not establish paid discovery against this source slice’s legacy schema. Subscription schema retirement and functioning canonical UUID facade/admission consumers remain one downstream receiving boundary, including the V1028 retained archive, V1029 canonical table and dependent lifecycle/dispatch/terminal-resolution storage. No numeric fallback or second subscription table is introduced. Private `REALMS`, registered browser/direct scope consumption, live [player-admission entitlement integration](#player-admission-entitlement-source-preparation), JOIN consumer migration, default registration and gameplay admission remain gaps. 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. Focused signing and orchestration cases use real local signing and bootstrap verification with controlled source and transaction inputs. The retained pre-V1028 PostgreSQL scope cases preserve exact signed UUID/V2 hash, digest and provenance bytes without membership, pair, JOIN or 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. Current-head CI remains required after source changes. @@ -521,7 +545,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `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.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. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. 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. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. 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); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [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. Their canonical UUID schema prerequisites V1028/V1029 and existing facade convergence are carried by [#3389](https://github.com/benhook1013/FireMUD/pull/3389) and [#3390](https://github.com/benhook1013/FireMUD/pull/3390). This source carrier still retains the legacy numeric schema; `CreateSubscription` still fails closed before mutation. Subscription lifecycle processing, reconciliation, entitlement/availability enforcement, caller-stable creation identity, active-subscription deletion guards, per-subscription binding, 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.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); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [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. Their canonical UUID schema prerequisites V1028/V1029, existing facade convergence and initial provider-write source are carried by [#3390](https://github.com/benhook1013/FireMUD/pull/3390); paid first-invoice checkout completion remains open there. This source carrier still retains the legacy numeric schema; `CreateSubscription` still fails closed before mutation. Subscription lifecycle processing, reconciliation, entitlement/availability enforcement, caller-stable creation identity, active-subscription deletion guards, per-subscription binding, 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.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. | @@ -760,6 +784,8 @@ R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/Post ## Validation and Proof +The [local source-foundation preparation](#local-source-foundation-preparation) records selected unit/mTLS, affected source compilation and enabled static/format proof for the reconstructed source before the provider-write transfer. Those results and historical #3389, #3390 and #3403 results retain their original comparisons; the reduced boundary now has the affected compilation and 51-case focused Account proof recorded above, not a repeated whole-foundation qualification. Physical PostgreSQL qualification and fresh positive runtime Smoke remain receiving obligations; the independently supported parent runtime is preserved, not requalified by source-only checks. + The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passed all five native region-owner cases, including this cut, and the inherited protected-admission concurrency case; its aggregate still failed Entity test SpotBugs. The extracted Entity producer's R890/R891/R893 history is recorded separately below. This is bounded refusal proof and does not establish recovery or production activation. diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index c8467b09e1..1643550e98 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -3939,10 +3939,9 @@ if run_preview_derive_dispatch \ exit 1 fi grep -Fxq \ - '::error title=Stale preview head SHA::Supplied head SHA does not equal the current pull request head.' \ + '::error title=Noncanonical preview head SHA::Expected lowercase hexadecimal input.' \ "$preview_derive_invalid_error" -grep -Fxq 'api repos/example/FireMUD/pulls/901' \ - "${preview_derive_invalid_output}.gh.log" +test ! -e "${preview_derive_invalid_output}.gh.log" preview_derive_default_output="$TEMP_DIR/preview-derive-default.output" run_preview_derive_dispatch \ 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 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/account/v1/tenant_operation_entitlement_read.proto b/protos/account/v1/tenant_operation_entitlement_read.proto new file mode 100644 index 0000000000..81abb10bee --- /dev/null +++ b/protos/account/v1/tenant_operation_entitlement_read.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Private Account owner read for exact same-namespace World Management over workload mTLS. +// Explicit eligibility source selection creates neither capacity nor player admission authority. +service AccountTenantOperationEntitlementReadService { + rpc ReadTenantOperationEntitlement(ReadTenantOperationEntitlementRequest) + returns (ReadTenantOperationEntitlementResponse); +} + +// Repeated transport members must each have exactly one value. This preserves duplicate scalar +// occurrences for closed-schema validation instead of protobuf's singular last-value-wins parsing. +message ReadTenantOperationEntitlementRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated string tenant_id = 3; + repeated string request_id = 4; + // Exactly PAID_HOSTING or NON_PAID_DEMO. No default, inference, or fallback. + repeated string source_kind = 5; +} + +message ReadTenantOperationEntitlementResponse { + repeated ReadTenantOperationEntitlementRequest request = 1; + // Exactly one existing strict canonical TENANT_OPERATION value, bounded to 64 KiB. + // Its callerWorkload is derived from the authenticated peer, never request data. + 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..51865174cf 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -180,7 +180,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") @@ -189,6 +189,19 @@ 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/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") + 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") } } 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..f65a0db6b1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java @@ -0,0 +1,205 @@ +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()) { + 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"); + } + Actor decoded; + try { + decoded = + new Actor( + parseUuid(actor.getCharacterUuid()), actor.getDisplayName(), actor.getLevel()); + } catch (IllegalArgumentException invalidActor) { + throw new IllegalStateException("Entity bootstrap discovery actor is malformed"); + } + actors.add(decoded); + 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/client/StripeBillingPrerequisiteObserver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java index c75decfffe..142612ca4e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java @@ -3,6 +3,7 @@ import com.stripe.exception.StripeException; import com.stripe.model.Customer; import com.stripe.model.PaymentMethod; +import com.stripe.net.RequestOptions; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -77,11 +78,17 @@ public StripeBillingPrerequisiteObserver( * not-found response) remains unresolved with its original cause; it never proves absence. */ public Result observe(ExpectedBinding expected) { + return observe(expected, RequestOptions.getDefault()); + } + + // The held hosting provisioner supplies its validated finite transport policy for both reads. + Result observe(ExpectedBinding expected, RequestOptions requestOptions) { Objects.requireNonNull(expected, "expected binding is required"); + Objects.requireNonNull(requestOptions, "request options are required"); Instant readStartedAt = clock.instant(); Customer customer; try { - customer = stripeClient.customers().retrieve(expected.providerCustomerId()); + customer = stripeClient.customers().retrieve(expected.providerCustomerId(), requestOptions); } catch (StripeException providerFailure) { return unresolved(expected, readStartedAt, clock.instant(), providerFailure); } @@ -101,7 +108,10 @@ public Result observe(ExpectedBinding expected) { PaymentMethod paymentMethod; try { - paymentMethod = stripeClient.paymentMethods().retrieve(expected.providerPaymentMethodId()); + paymentMethod = + stripeClient + .paymentMethods() + .retrieve(expected.providerPaymentMethodId(), requestOptions); } catch (StripeException providerFailure) { return unresolved(expected, readStartedAt, clock.instant(), providerFailure); } 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/entity/RetainedSubscriptionEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/RetainedSubscriptionEvidence.java new file mode 100644 index 0000000000..595c15b6bc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/RetainedSubscriptionEvidence.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.accountservice.entity; + +import java.time.LocalDateTime; +import java.util.UUID; + +/** + * Immutable historical numeric subscription evidence, never current billing or entitlement + * authority. All identifiers and counters here are retained values, not canonical identity or + * billing sequence. + */ +public record RetainedSubscriptionEvidence( + Long id, + Long accountId, + String planId, + String status, + LocalDateTime startedAt, + LocalDateTime endedAt, + Long tenantId, + long entitlementVersion, + UUID tenantAuthorityGeneration) {} 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 f1c7283e82..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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -17,6 +18,9 @@ import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Authorization; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.LockedTarget; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import org.jooq.DSLContext; @@ -73,6 +77,283 @@ public AccountHostingSubscriptionLifecycleRepository( dsl, new AccountAuthorityOutboxRepository(dsl), billing, tenantIdentity, generations); } + /** Locked read capture only. No journal, intent, audit or fence changes precede final auth. */ + public ResolutionPreparation prepareTerminalResolution(Request request) { + requireTransaction(); + Objects.requireNonNull(request); + var original = intents.findCreation(request.creationRequestId()).orElseThrow(); + if (!request.tenantId().equals(original.tenantId()) + || !request.subscriptionId().equals(original.subscriptionId()) + || !request.actorAccountId().equals(original.owner().accountUuid())) { + throw new FenceRejectedException("Exact same-owner terminal lifecycle target rejected"); + } + Record journal = + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = ? FOR UPDATE", + request.resolutionRequestId()); + // Exact committed-result disclosure belongs to the original authenticated actor. It must not + // select a successor subscription or require the canceled predecessor to remain current. + // Only a new mutation takes today's current-row/owner/instrument fence, in its original order. + long currentVersion; + if (journal == null) { + var observedCurrent = intents.findCurrentByTenant(original.tenantId()).orElseThrow(); + currentVersion = + intents.lockForLifecycle(original.requestId(), observedCurrent.rowVersion()).rowVersion(); + } else { + currentVersion = journal.get("result_row_version", Long.class); + } + Record failed = operationForUpdate(request.failedRequestId()); + if (!request.creationRequestId().equals(failed.get("creation_request_id", UUID.class)) + || !request.subscriptionId().equals(failed.get("subscription_id", UUID.class)) + || !"BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(failed.get("state", String.class)) + || request.expectedFailedOperationVersion() != failed.get("row_version", Long.class)) { + throw new FenceRejectedException("Exact same-owner terminal lifecycle target rejected"); + } + ExpectedBinding binding = + expected(original, failed.get("provider_subscription_id", String.class)); + if (journal != null) { + if (!request.digest().equals(journal.get("request_digest", String.class)) + || !Arrays.equals(request.payload(), journal.get("request_payload", byte[].class))) { + throw new FenceRejectedException("IDEMPOTENCY_CONFLICT: terminal resolution tuple changed"); + } + Record receipt = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_receipts WHERE request_id = ?", + request.resolutionRequestId())); + if (!"COMMITTED".equals(journal.get("state", String.class)) + || !"canceled".equals(receipt.get("status", String.class)) + || !journal + .get("receipt_digest", String.class) + .equals(receipt.get("receipt_digest", String.class))) { + throw new FenceRejectedException("Terminal resolution receipt readback differs"); + } + new AccountAuditOutboxRepository(dsl) + .findCanonicalTenantEnvelopeForUpdate(request.auditEventId()) + .filter( + audit -> + request.digest().equals(audit.payloadDigest()) + && "HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED".equals(audit.eventType()) + && request.tenantId().equals(audit.tenantUuid())) + .orElseThrow( + () -> new FenceRejectedException("Terminal resolution audit readback differs")); + return new ResolutionPreparation( + request, + binding, + original.owner().accountUuid(), + currentVersion, + now(), + now(), + new TransitionResult( + request.resolutionRequestId(), + Outcome.COMMITTED, + journal.get("result_row_version", Long.class), + null)); + } + if (request.expectedSubscriptionVersion() != currentVersion + || !request + .failedRequestId() + .equals( + links(request.subscriptionId()).get("lifecycle_inflight_request_id", UUID.class))) { + throw new FenceRejectedException("Terminal resolution lost its exact failed current fence"); + } + Instant captured = now(); + Instant deadline = + earlier( + captured.plus(limits.lease()), + captured.plusMillis(failed.get("observation_age_millis", Long.class))); + return new ResolutionPreparation( + request, binding, original.owner().accountUuid(), currentVersion, captured, deadline, null); + } + + /** + * Final cancellation-only owner mutation. The mandatory callback runs under exact target locks + * immediately before writes; callback inputs/outputs alone do not establish Account authority. If + * the callback throws an authentication denial, the caller may catch it outside this method and + * commit its own failed-login accounting because this method has made no repository writes before + * invoking the callback. A repository write added before the callback removes this narrow + * exception; all other failures require rollback. Commit failures remain the caller transaction + * manager’s responsibility. + */ + public TransitionResult applyTerminalResolution( + ResolutionPreparation prepared, + StripeHostingSubscriptionObserver.Result result, + Authorization authorization) { + requireTransaction(); + Objects.requireNonNull(prepared); + Objects.requireNonNull(authorization, "Explicit final Account authorization callback required"); + Request request = prepared.request; + ResolutionPreparation locked = prepareTerminalResolution(request); + Instant evaluated = now(); + if (locked.replay == null) { + if (prepared.replay != null + || !prepared.binding.equals(locked.binding) + || evaluated.isBefore(prepared.capturedAt) + || !evaluated.isBefore(prepared.deadline) + || !(result instanceof ObservedSubscription observed) + || !observed.providerStatusIsCanceled() + || observed.readStartedAt().isBefore(prepared.capturedAt) + || observed.observedAt().isAfter(evaluated)) { + throw new FenceRejectedException( + "Fresh exact canceled SDK evidence required for resolution"); + } + requireObservedBinding(prepared.binding, observed); + Record failed = operationForUpdate(request.failedRequestId()); + var decision = retainedPolicy(failed).evaluate(observed, evaluated, null); + if (!decision.resolved() || decision.status() != Status.CANCELED) { + throw new FenceRejectedException("Terminal cancellation evidence expired or is unresolved"); + } + } + Instant authenticationStarted = now(); + var actor = + Objects.requireNonNull( + authorization.requireAuthorized( + new LockedTarget(request, locked.billingOwnerAccountId, locked.currentVersion))); + Instant authenticated = now(); + if (!request.actorAccountId().equals(actor.actorAccountId()) + || !request.controlUiIssuanceOperationId().equals(actor.controlUiIssuanceOperationId()) + || !request.controlUiTokenHash().equals(actor.controlUiTokenHash()) + || actor.authenticatedAt().isBefore(authenticationStarted) + || actor.authenticatedAt().isAfter(authenticated)) { + throw new FenceRejectedException( + "Final primary-authentication source differs from exact actor"); + } + if (locked.replay != null) return locked.replay; + if (!authenticated.isBefore(prepared.deadline)) { + throw new FenceRejectedException("Terminal resolution capture expired during authorization"); + } + new AccountAuditOutboxRepository(dsl) + .appendCanonicalTenant( + request.auditEventId(), + request.tenantId().toString(), + "HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED", + new String(request.payload(), StandardCharsets.UTF_8)); + UUID attemptId = UUID.randomUUID(); + dsl.execute( + "INSERT INTO subscription_lifecycle_terminal_resolutions (resolution_request_id, failed_request_id, creation_request_id, " + + "subscription_id, tenant_id, expected_failed_version, expected_subscription_version, actor_account_id, " + + "control_ui_issuance_operation_id, control_ui_token_hash, audit_event_id, audit_reason, request_payload, request_digest, " + + "attempt_id, captured_at, expires_at, authenticated_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?::timestamptz, 'PREPARED')", + request.resolutionRequestId(), + request.failedRequestId(), + request.creationRequestId(), + request.subscriptionId(), + request.tenantId(), + request.expectedFailedOperationVersion(), + request.expectedSubscriptionVersion(), + request.actorAccountId(), + request.controlUiIssuanceOperationId(), + request.controlUiTokenHash(), + request.auditEventId(), + request.auditReason(), + request.payload(), + request.digest(), + attemptId, + utc(prepared.capturedAt), + utc(prepared.deadline), + utc(actor.authenticatedAt())); + if (dsl.execute( + "INSERT INTO subscription_lifecycle_operations (request_id, creation_request_id, subscription_id, tenant_id, expected_row_version, " + + "reserved_row_version, provider_subscription_id, provisioning_attempt_id, request_payload, request_digest, state, row_version, " + + "max_attempts, max_stalled_attempts, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, deadline_at, retry_at, created_at) " + + "SELECT ?, creation_request_id, subscription_id, tenant_id, ?, ?, provider_subscription_id, provisioning_attempt_id, ?, ?, 'PENDING', 1, " + + "1, 1, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, ?::timestamptz, ?::timestamptz, ?::timestamptz " + + "FROM subscription_lifecycle_operations WHERE request_id = ? AND state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' AND row_version = ?", + request.resolutionRequestId(), + request.expectedSubscriptionVersion(), + request.expectedSubscriptionVersion() + 1, + request.payload(), + request.digest(), + utc(prepared.deadline), + utc(prepared.capturedAt), + utc(prepared.capturedAt), + request.failedRequestId(), + request.expectedFailedOperationVersion()) + != 1) { + throw new FenceRejectedException("Terminal resolution exact failed-operation copy rejected"); + } + if (dsl.execute( + "UPDATE subscription SET lifecycle_inflight_request_id = ?, row_version = row_version + 1 " + + "WHERE subscription_id = ? AND row_version = ? AND lifecycle_inflight_request_id = ? AND superseded_at IS NULL", + request.resolutionRequestId(), + request.subscriptionId(), + request.expectedSubscriptionVersion(), + request.failedRequestId()) + != 1) { + throw new FenceRejectedException("Terminal resolution expected-current CAS rejected"); + } + dsl.execute( + "INSERT INTO subscription_lifecycle_attempts (attempt_id, request_id, attempt_number, started_at, expires_at) VALUES (?, ?, 1, ?::timestamptz, ?::timestamptz)", + attemptId, + request.resolutionRequestId(), + utc(prepared.capturedAt), + utc(prepared.deadline)); + dsl.execute( + "UPDATE subscription_lifecycle_operations SET attempt_count = 1, last_attempt_id = ?, row_version = row_version + 1 WHERE request_id = ?", + attemptId, + request.resolutionRequestId()); + TransitionResult committed = + apply( + new Preparation( + request.resolutionRequestId(), + attemptId, + prepared.binding, + Outcome.READY, + null, + request.expectedSubscriptionVersion() + 1), + result); + if (committed.outcome() != Outcome.COMMITTED) + throw new FenceRejectedException("Cancellation resolution did not commit"); + dsl.execute( + "UPDATE subscription_lifecycle_terminal_resolutions SET state = 'COMMITTED', result_row_version = ?, " + + "receipt_digest = (SELECT receipt_digest FROM subscription_lifecycle_receipts WHERE request_id = ?), committed_at = ?::timestamptz " + + "WHERE resolution_request_id = ? AND state = 'PREPARED'", + committed.committedRowVersion(), + request.resolutionRequestId(), + utc(now()), + request.resolutionRequestId()); + return committed; + } + + public static final class ResolutionPreparation { + private final Request request; + private final ExpectedBinding binding; + private final UUID billingOwnerAccountId; + private final long currentVersion; + private final Instant capturedAt; + private final Instant deadline; + private final TransitionResult replay; + + private ResolutionPreparation( + Request request, + ExpectedBinding binding, + UUID billingOwnerAccountId, + long currentVersion, + Instant capturedAt, + Instant deadline, + TransitionResult replay) { + this.request = request; + this.binding = binding; + this.billingOwnerAccountId = billingOwnerAccountId; + this.currentVersion = currentVersion; + this.capturedAt = capturedAt; + this.deadline = deadline; + this.replay = replay; + } + + public Request request() { + return request; + } + + public ExpectedBinding binding() { + return binding; + } + + public TransitionResult replayResult() { + return replay; + } + } + /** * Reserves currentness before an SDK read; stable request replay never issues a second * transition. @@ -1038,8 +1319,9 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId /** * Inserts a separate immutable provider-dispatch boundary after revalidating the exact live - * private worker claim. Only a new first-attempt insertion may carry initial-call permission. - * Preexisting unknown migration guards and all replayed/recovered attempts reconcile only. + * private worker claim. Only a newly inserted first-dispatch receipt may carry initial-call + * permission, even if an earlier worker attempt expired without dispatching. Preexisting unknown + * migration guards and all replayed dispatches reconcile only. */ public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID dispatchId) { requireTransaction(); @@ -1064,7 +1346,6 @@ public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID requireDispatchBinding(retained, receipt); boolean initial = inserted == 1 - && retained.attemptNumber() == 1 && "FIRST_DISPATCH".equals(receipt.classification()) && retained.attemptId().equals(receipt.firstAttemptId()); return providerDispatch(retained, receipt, initial, false, transactionId()); @@ -1265,6 +1546,10 @@ public ExpectedBinding expectedBinding(String providerId) { * Ends one worker attempt without asserting provider absence or cancellation. Failure keeps the * subscription provisioning and its reservation held; even terminal reconciliation failure is * unresolved billing work. The caller must commit this result rather than throw it away. + * + *

An exact retained attempt that expires before the absolute deadline returns {@link + * Disposition#ATTEMPT_EXPIRED} without changing its work or reservation, leaving recovery to the + * next claimant. */ public Disposition deferUnresolved(ProvisioningClaim claim) { requireTransaction(); @@ -1290,7 +1575,9 @@ public Disposition deferUnresolved(ProvisioningClaim claim) { return fail(work, "ABSOLUTE_DEADLINE", now).disposition(); } if (!now.isBefore(claim.expiresAt())) { - throw new FenceRejectedException("Expired attempt cannot record provider completion"); + // 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. + return Disposition.ATTEMPT_EXPIRED; } if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { return fail(work, "ATTEMPT_BUDGET", now).disposition(); @@ -1389,7 +1676,9 @@ public enum Disposition { public record ClaimResult(Disposition disposition, ProvisioningClaim claim) {} /** - * Private construction prevents mistaking caller-supplied status/version booleans for a claim. + * Private construction prevents mistaking caller-supplied status/version booleans for a claim. A + * claim's attempt number never grants or denies provider creation. Only an independently read + * ProviderDispatch carries initial-call permission from the retained first-dispatch receipt. */ public static final class ProvisioningClaim { private final AccountSubscriptionCreationRecord creation; @@ -1437,10 +1726,6 @@ public Instant claimedAt() { public Instant expiresAt() { return expiresAt; } - - public boolean reconciliationRequiredBeforeCreate() { - return attemptNumber > 1; - } } /** Frozen into durable work on its first claim; later configuration cannot widen its budget. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java new file mode 100644 index 0000000000..e57d831350 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** + * Credential-free cancellation-resolution comparison data. Construction grants no authorization. + * The unregistered owner must invoke an explicit final authorization source under its SQL locks; + * actual Account actor/primary-authentication integration belongs to its outer composition. + */ +public final class AccountHostingSubscriptionTerminalResolution { + private AccountHostingSubscriptionTerminalResolution() {} + + public record Request( + UUID resolutionRequestId, + UUID failedRequestId, + UUID creationRequestId, + UUID subscriptionId, + UUID tenantId, + long expectedFailedOperationVersion, + long expectedSubscriptionVersion, + UUID actorAccountId, + UUID controlUiIssuanceOperationId, + String controlUiTokenHash, + UUID auditEventId, + String auditReason) { + public Request { + for (UUID id : + new UUID[] { + resolutionRequestId, + failedRequestId, + creationRequestId, + subscriptionId, + tenantId, + actorAccountId, + controlUiIssuanceOperationId, + auditEventId + }) { + AccountBillingCustomerRecord.requireUuid(id); + } + if (resolutionRequestId.equals(failedRequestId) + || expectedFailedOperationVersion < 1 + || expectedSubscriptionVersion < 1 + || expectedSubscriptionVersion >= Long.MAX_VALUE - 2) { + throw new IllegalArgumentException( + "Distinct resolution identity and advanceable versions required"); + } + requireTokenHash(controlUiTokenHash); + auditReason = requireReason(auditReason); + } + + public byte[] payload() { + return AccountHostingSubscriptionLifecycleEvidence.encode( + Map.ofEntries( + Map.entry("schemaVersion", "account-hosting-terminal-resolution/v1"), + Map.entry("outcome", "CANCELED"), + Map.entry("resolutionRequestId", resolutionRequestId.toString()), + Map.entry("failedRequestId", failedRequestId.toString()), + Map.entry("creationRequestId", creationRequestId.toString()), + Map.entry("subscriptionId", subscriptionId.toString()), + Map.entry("tenantId", tenantId.toString()), + Map.entry( + "expectedFailedOperationVersion", Long.toString(expectedFailedOperationVersion)), + Map.entry("expectedSubscriptionVersion", Long.toString(expectedSubscriptionVersion)), + Map.entry("actorAccountId", actorAccountId.toString()), + Map.entry("controlUiIssuanceOperationId", controlUiIssuanceOperationId.toString()), + Map.entry("controlUiTokenHash", controlUiTokenHash), + Map.entry("auditEventId", auditEventId.toString()), + Map.entry("auditReason", auditReason))); + } + + public String digest() { + return AccountHostingSubscriptionLifecycleEvidence.digest(payload()); + } + } + + public record LockedTarget( + Request request, UUID billingOwnerAccountId, long currentSubscriptionVersion) { + public LockedTarget { + Objects.requireNonNull(request); + AccountBillingCustomerRecord.requireUuid(billingOwnerAccountId); + } + } + + /** + * Same-transaction primary-authentication source identifiers, not authority from construction. + */ + public record AuthorizedActor( + UUID actorAccountId, + UUID controlUiIssuanceOperationId, + String controlUiTokenHash, + Instant authenticatedAt) { + public AuthorizedActor { + AccountBillingCustomerRecord.requireUuid(actorAccountId); + AccountBillingCustomerRecord.requireUuid(controlUiIssuanceOperationId); + requireTokenHash(controlUiTokenHash); + Objects.requireNonNull(authenticatedAt); + } + } + + /** + * Must revalidate the exact actual Account actor and fresh primary authentication in this SQL. + */ + @FunctionalInterface + public interface Authorization { + AuthorizedActor requireAuthorized(LockedTarget target); + } + + private static String requireReason(String reason) { + String normalized = Normalizer.normalize(Objects.requireNonNull(reason), Normalizer.Form.NFC); + try { + int bytes = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(normalized)) + .remaining(); + if (bytes > 1000 + || normalized.indexOf(0) >= 0 + || normalized + .codePoints() + .allMatch(AccountHostingSubscriptionTerminalResolution::sharedWhitespace)) { + throw new IllegalArgumentException( + "Nonblank credential-free audit reason of at most 1000 UTF-8 bytes required"); + } + } catch (CharacterCodingException failure) { + throw new IllegalArgumentException("Audit reason must contain Unicode scalars", failure); + } + return normalized; + } + + private static boolean sharedWhitespace(int value) { + return (value >= 0x0009 && value <= 0x000D) + || value == 0x0020 + || value == 0x0085 + || value == 0x00A0 + || value == 0x1680 + || (value >= 0x2000 && value <= 0x200A) + || value == 0x2028 + || value == 0x2029 + || value == 0x202F + || value == 0x205F + || value == 0x3000; + } + + private static void requireTokenHash(String hash) { + if (hash == null || !hash.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact native control-ui token hash required"); + } + } +} 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/security/AccountTenantOperationEntitlementWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java new file mode 100644 index 0000000000..2ac1413e2b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java @@ -0,0 +1,75 @@ +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.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Exact method/World gate deriving its private assertion from transport TLS, never caller context. + */ +public final class AccountTenantOperationEntitlementWorkloadGuard implements ServerInterceptor { + private final Context.Key authenticatedCaller = + Context.key("tenant-operation-world-peer"); + private final String expectedWorkload; + + public AccountTenantOperationEntitlementWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + expectedWorkload = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + } + + /** Only this guard's TLS interception can supply the private method-authorized assertion. */ + public String requireAuthenticatedWorldCaller() { + if (!expectedWorkload.equals(authenticatedCaller.get()) || hasSessionContext()) { + throw Status.UNAUTHENTICATED + .withDescription("Protected World 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() + || !AccountTenantOperationEntitlementReadServiceGrpc + .getReadTenantOperationEntitlementMethod() + .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 World 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/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java new file mode 100644 index 0000000000..bb0d77e073 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -0,0 +1,688 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.StatusRuntimeException; +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.AccountSubscriptionIntentRepository.FenceRejectedException; +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); + transaction.setTimeout(5); + } + + /** 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); + }; + try { + evidence.requireCurrentAt(now()); + } catch (IllegalArgumentException expired) { + // This final post-commit check only rejects an expired or future source observation. + throw unavailable(); + } + return evidence; + } + + private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( + Request request, VerifiedCaller caller, Prepared prepared) { + var fence = + inSourceTransaction( + () -> { + try { + return hosting.prepareCurrentRead(request.tenantId()); + } catch (FenceRejectedException rejected) { + throw unavailable(); + } + }); + 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()); + final AccountHostingSubscriptionCurrentReceipt receipt; + try { + receipt = hosting.readCurrent(fence, observation); + } catch (FenceRejectedException rejected) { + throw unavailable(); + } + 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 (!"SHARED".equals(scope.playableStateScope())) throw targetPrecondition(); + if (!request.target().equals(selector(request, scope))) throw targetPrecondition(); + 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 SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } + + /** Current owner evidence cannot be supplied; not a configuration or codec failure. */ + public static final class SourceUnavailableException extends IllegalStateException { + public SourceUnavailableException() { + super("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable"); + } + } + + private static TargetPreconditionException targetPrecondition() { + return new TargetPreconditionException(); + } + + /** The current target is unsupported or differs from the exact retained selectors. */ + public static final class TargetPreconditionException extends IllegalStateException { + public TargetPreconditionException() { + super( + "ENTITLEMENT_TARGET_PRECONDITION: current target does not match the supported retained target"); + } + } + + 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); + try { + var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); + if (!selector.equals(resolved.selector())) throw targetPrecondition(); + requireSupportedTarget(resolved.currentTarget()); + try { + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + } catch (IllegalArgumentException changedTarget) { + // Only this exact target comparison is a precondition, not arbitrary codec failures. + throw targetPrecondition(); + } + var result = + Objects.requireNonNull( + targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); + if (!resolved.strictSelector().equals(result.selector()) + || !resolved.currentTarget().equals(result.currentTarget())) throw targetPrecondition(); + requireSupportedTarget(result.currentTarget()); + return result; + } catch (CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException failure) { + throw unavailable(); + } catch (StatusRuntimeException failure) { + switch (failure.getStatus().getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, ABORTED -> throw unavailable(); + case FAILED_PRECONDITION -> throw targetPrecondition(); + default -> throw failure; + } + } + } + + private static void requireSupportedTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target target) { + if (!"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw targetPrecondition(); + } + + 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(); + requireSupportedTarget(current); + Map binding = new LinkedHashMap<>(); + binding.put("targetClass", "PUBLIC_PRODUCTION"); + binding.put("characterCreationPolicy", current.characterCreationPolicy()); + 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/AccountTenantOperationEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java new file mode 100644 index 0000000000..a576f803db --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java @@ -0,0 +1,344 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +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.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed Account source owner for TENANT_OPERATION evaluations only. + * + *

Held source boundary: this owner and its peer-qualified receiver are manually composed and + * unregistered. The receiver must authenticate and method-authorize the exact World Management peer + * before constructing Request; parsing a workload URI and supplying UUIDs never grants authority. + * Capacity commitment, durable evaluation replay and player admission remain outside this boundary. + * Paid and demo selection is explicit and never falls back on absence. Pending/provisioning without + * a genuine current receipt remains unavailable. Every returned canonical value is captured before + * its source transaction commits; a failed commit returns no value. + */ +public final class AccountTenantOperationEntitlementOwner { + private final AccountHostingSubscriptionLifecycleService hosting; + private final AccountDemoTenantEntitlementRepository demos; + private final TransactionTemplate transaction; + private final Clock clock; + private final String expectedWorkload; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected SDK/repository collaborators remain private; copying would break owner composition.") + public AccountTenantOperationEntitlementOwner( + AccountHostingSubscriptionLifecycleService hosting, + AccountDemoTenantEntitlementRepository demos, + PlatformTransactionManager transactions, + Clock clock, + String workloadNamespace) { + this.hosting = Objects.requireNonNull(hosting); + this.demos = Objects.requireNonNull(demos); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical World Management namespace is required"); + } + expectedWorkload = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service") + .orElseThrow() + .uri(); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.setTimeout(5); + } + + public RuntimeTenantOperationEntitlementEvidence evaluatePaid(Request request) { + requireRequest(request); + return hosting.readCurrentAndCapture(request.tenantId(), receipt -> paid(request, receipt)); + } + + public RuntimeTenantOperationEntitlementEvidence evaluateDemo(Request request) { + requireRequest(request); + requireNoAmbientTransaction(); + return Objects.requireNonNull( + transaction.execute( + status -> { + requireSourceTransaction(); + DemoTenantEntitlementSnapshot snapshot = demos.readCurrent(request.tenantId()); + if (!request.tenantId().equals(snapshot.canonicalTenantId())) { + throw unavailable("Demo source targets another tenant"); + } + Map facts = + facts( + request.tenantId(), + "NON_PAID_DEMO", + snapshot.subscriptionStatus(), + snapshot.gameplayAvailable(), + snapshot.allowPublicJoin(), + snapshot.allowNewGameplayBindings(), + snapshot.allowNewInstanceStarts(), + quotas( + snapshot.quotas().maxActiveSessions(), + snapshot.quotas().maxConcurrentGameInstances(), + snapshot.quotas().maxStorageBytes()), + snapshot.entitlementVersion(), + snapshot.tenantBillingSequence(), + snapshot.tenantAuthorityGeneration(), + snapshot.tenantAuthorityOutboxStreamKey(), + snapshot.tenantAuthorityOutboxSequence(), + snapshot.tenantAuthorityEventId(), + snapshot.tenantAuthorityEventDigest()); + Map source = new LinkedHashMap<>(); + source.put("sourceEvidenceDigest", snapshot.sourceEvidence().evidenceDigest()); + source.put( + "tenantAuthoritySourceVersion", + Long.toString(snapshot.tenantAuthoritySourceVersion())); + source.put("billingStream", snapshot.outboxStreamKey()); + source.put("billingSequence", Long.toString(snapshot.tenantBillingSequence())); + source.put("billingEventId", snapshot.eventId().toString()); + source.put("billingEventDigest", snapshot.eventDigest()); + return capture(request, facts, source, now()); + })); + } + + private RuntimeTenantOperationEntitlementEvidence paid( + Request request, AccountHostingSubscriptionCurrentReceipt receipt) { + requireSourceTransaction(); + Objects.requireNonNull(receipt, "Current hosting receipt is required"); + Instant evaluatedAt = now(); + if (!request.tenantId().equals(receipt.current().tenantId()) + || receipt.evaluatedAt() == null + || receipt.validUntil() == null + || evaluatedAt.isBefore(receipt.evaluatedAt()) + || !evaluatedAt.isBefore(receipt.validUntil())) { + throw unavailable("Current hosting receipt is not fresh for this tenant"); + } + var event = receipt.tenantAuthorityEvent(); + if (!request.tenantId().equals(event.tenantId()) + || receipt.tenantBillingSequence() != event.tenantBillingSequence() + || !receipt.billingEventId().equals(event.tenantBillingEventId()) + || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest())) { + throw unavailable("Hosting receipt and current tenant authority disagree"); + } + var quote = receipt.current().planQuote(); + Map facts = + facts( + request.tenantId(), + "PAID_HOSTING", + receipt.subscriptionStatus().storageValue(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + quotas( + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes()), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + event.tenantAuthorityGeneration(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + Map source = new LinkedHashMap<>(); + source.put("receiptRequestId", receipt.receiptRequestId().toString()); + source.put("subscriptionId", receipt.current().subscriptionId().toString()); + source.put("subscriptionRowVersion", Long.toString(receipt.current().rowVersion())); + source.put("creationRequestId", receipt.current().creationRequestId().toString()); + source.put("retainedPlanQuoteDigest", quote.digest()); + source.put("sourceEvidenceDigest", event.sourceEvidence().evidenceDigest()); + source.put("tenantAuthoritySourceVersion", Long.toString(event.tenantAuthoritySourceVersion())); + source.put("billingStream", event.tenantBillingStreamKey()); + source.put("billingSequence", Long.toString(receipt.tenantBillingSequence())); + source.put("billingEventId", receipt.billingEventId().toString()); + source.put("billingEventDigest", receipt.billingEventDigest()); + return capture(request, facts, source, evaluatedAt); + } + + private static Map facts( + UUID tenantId, + String sourceKind, + String subscriptionStatus, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + Map quotas, + long entitlementVersion, + long billingSequence, + long generation, + String authorityStream, + long authoritySequence, + UUID eventId, + String eventDigest) { + if (!TenantAuthorityEventV1Codec.streamKey(tenantId).equals(authorityStream)) { + throw unavailable("Tenant authority stream differs from requested tenant"); + } + Map facts = new LinkedHashMap<>(); + facts.put("schema", RuntimeTenantOperationEntitlementEvidence.SCHEMA); + facts.put("variant", RuntimeTenantOperationEntitlementEvidence.VARIANT); + facts.put("authorityAvailability", "AVAILABLE"); + facts.put("bundleVersion", "1"); + facts.put("tenantId", tenantId.toString()); + facts.put("sourceKind", sourceKind); + facts.put("subscriptionStatus", subscriptionStatus); + facts.put("provisioningStatus", null); + facts.put("gameplayAvailable", gameplayAvailable); + facts.put("allowPublicJoin", allowPublicJoin); + facts.put("allowNewGameplayBindings", allowNewGameplayBindings); + facts.put("allowNewInstanceStarts", allowNewInstanceStarts); + facts.put("quotas", quotas); + facts.put("entitlementVersion", Long.toString(entitlementVersion)); + facts.put("tenantBillingSequence", Long.toString(billingSequence)); + facts.put("tenantAuthorityGeneration", Long.toString(generation)); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", + Long.toString(generation), + "tenantBillingSequence", + Long.toString(billingSequence), + "outboxStreamKey", + authorityStream, + "outboxSequence", + Long.toString(authoritySequence)); + facts.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", Map.of(tenantId.toString(), Long.toString(generation)), + "tenantBillingCutoff", Map.of(tenantId.toString(), cutoff))); + facts.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + authorityStream, + "outboxSequence", + Long.toString(authoritySequence), + "sourceEventId", + eventId.toString(), + "sourceEventDigest", + eventDigest))); + return facts; + } + + private static RuntimeTenantOperationEntitlementEvidence capture( + Request request, Map facts, Map source, Instant evaluatedAt) { + requireSourceTransaction(); + String snapshot = + RuntimeTenantOperationEntitlementEvidence.canonicalDigest( + Map.of( + "schema", + "tenant-operation-entitlement-snapshot/v1", + "committedFacts", + new LinkedHashMap<>(facts), + "committedSource", + source)); + facts.put("requestId", request.requestId().toString()); + facts.put("callerWorkload", request.authenticatedCallerWorkload()); + facts.put("evaluatedAt", evaluatedAt.toString()); + facts.put("snapshotIdentity", snapshot); + facts.put( + "evaluationIdentity", + RuntimeTenantOperationEntitlementEvidence.canonicalDigest( + Map.of( + "schema", + "tenant-operation-entitlement-evaluation/v1", + "snapshotIdentity", + snapshot, + "tenantId", + request.tenantId().toString(), + "requestId", + request.requestId().toString(), + "callerWorkload", + request.authenticatedCallerWorkload(), + "evaluatedAt", + evaluatedAt.toString(), + "evaluationNonce", + UUID.randomUUID().toString()))); + return RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(facts); + } + + private static Map quotas(long sessions, long instances, long storage) { + return Map.of( + "maxActiveSessions", + Long.toString(sessions), + "maxConcurrentGameInstances", + Long.toString(instances), + "maxStorageBytes", + Long.toString(storage)); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + private void requireRequest(Request request) { + Objects.requireNonNull(request, "Tenant operation request is required"); + if (!expectedWorkload.equals(request.authenticatedCallerWorkload())) { + throw new IllegalArgumentException("Expected exact same-namespace World Management peer"); + } + } + + private static void requireSourceTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable( + "Complete runtime evidence requires its writable Account source transaction"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable("Demo evaluation refuses an ambient transaction or synchronization"); + } + } + + private static SourceUnavailableException unavailable(String message) { + return new SourceUnavailableException(message); + } + + /** An evaluated source cannot supply current evidence; not a configuration or codec failure. */ + public static final class SourceUnavailableException extends IllegalStateException { + public SourceUnavailableException(String message) { + super("ENTITLEMENT_UNAVAILABLE: " + message); + } + } + + /** Trusted transport assertion only; construction itself does not authenticate the caller. */ + public record Request(UUID tenantId, UUID requestId, String authenticatedCallerWorkload) { + public Request { + if (tenantId == null + || tenantId.equals(new UUID(0L, 0L)) + || requestId == null + || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Canonical non-nil tenant and request UUIDs are required"); + } + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) + .filter(identity -> identity.uri().equals(authenticatedCallerWorkload)) + .orElseThrow( + () -> + new IllegalArgumentException("Canonical authenticated workload is required")); + if (!"world-management-service".equals(peer.service())) { + throw new IllegalArgumentException("Tenant operation requires World Management"); + } + } + } +} 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..1a4efe1a70 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.Any; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.StatusProto; +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.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.shared.v1.ErrorDetail; +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 (AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException rejectedTarget) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } catch (AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException + | AccountGameplayAdmissionCallerVerifier.CallerUnavailableException + | AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException + | DemoTenantEntitlementException + | org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailableSource) { + fail(observer, Status.UNAVAILABLE); + return; + } catch (RuntimeException internalFailure) { + // Unexpected, configuration and codec faults are not retryable source outages. + fail(observer, Status.INTERNAL); + return; + } + try { + observer.onNext(response); + } catch (RuntimeException callbackFailure) { + fail(observer, Status.INTERNAL); + return; + } + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status) { + String message = "Player-admission entitlement evidence is unavailable"; + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.getCode().value()) + .setMessage(message) + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(status.getCode().name()) + .setMessage(message) + .build())) + .build())); + } +} 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 4564e1e49f..a8fba53811 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 @@ -260,6 +260,8 @@ public AccountServiceImpl( this.joinTransactionTemplate = new TransactionTemplate(transactionManager); this.joinTransactionTemplate.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.joinTransactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + this.joinTransactionTemplate.setReadOnly(false); this.passwordResetOwnerTransaction = new TransactionTemplate(transactionManager); this.passwordResetOwnerTransaction.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java new file mode 100644 index 0000000000..fe585d3476 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.Any; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.StatusProto; +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.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; +import net.firedevops.firemud.accountservice.security.AccountTenantOperationEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account owner receiver. No component annotation, capacity commit, or player gate. + */ +public final class AccountTenantOperationEntitlementGrpcService + extends AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceImplBase { + private final AccountTenantOperationEntitlementOwner owner; + private final String namespace; + private final AccountTenantOperationEntitlementWorkloadGuard guard; + + public AccountTenantOperationEntitlementGrpcService( + AccountTenantOperationEntitlementOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + this.guard = new AccountTenantOperationEntitlementWorkloadGuard(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(), + RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void readTenantOperationEntitlement( + ReadTenantOperationEntitlementRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String authenticatedCaller; + try { + authenticatedCaller = guard.requireAuthenticatedWorldCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + final RuntimeTenantOperationEntitlementGrpcCodec.Request request; + if (wire == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + try { + request = RuntimeTenantOperationEntitlementGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException invalid) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + final ReadTenantOperationEntitlementResponse response; + try { + var sourceRequest = + new AccountTenantOperationEntitlementOwner.Request( + request.tenantId(), request.requestId(), authenticatedCaller); + var evidence = + switch (request.sourceKind()) { + case PAID_HOSTING -> owner.evaluatePaid(sourceRequest); + case NON_PAID_DEMO -> owner.evaluateDemo(sourceRequest); + }; + response = RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence); + } catch (AccountTenantOperationEntitlementOwner.SourceUnavailableException + | AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException + | DemoTenantEntitlementException + | org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailableSource) { + fail(observer, Status.UNAVAILABLE); + return; + } catch (RuntimeException internalFailure) { + // Configuration mismatches and unexpected construction/codec failures are not retryable + // source outages. Never disclose exception messages or internal identifiers. + fail(observer, Status.INTERNAL); + return; + } + try { + observer.onNext(response); + } catch (RuntimeException callbackFailure) { + fail(observer, Status.INTERNAL); + return; + } + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status) { + String message = "Tenant-operation entitlement evidence is unavailable"; + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.getCode().value()) + .setMessage(message) + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(status.getCode().name()) + .setMessage(message) + .build())) + .build())); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java index 3e6c459e01..23ccaf27d4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java @@ -10,7 +10,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import net.firedevops.firemud.accountservice.service.PaymentService; import net.firedevops.firemud.common.LoggingUtil; import org.slf4j.Logger; @@ -23,7 +22,6 @@ public class PaymentServiceImpl implements PaymentService { private final AccountRepository accountRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; private final PaymentTransactionRepository paymentTransactionRepository; - private final SubscriptionRepository subscriptionRepository; private final StripeClient stripeClient; @SuppressFBWarnings( @@ -33,12 +31,10 @@ public PaymentServiceImpl( AccountRepository accountRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, PaymentTransactionRepository paymentTransactionRepository, - SubscriptionRepository subscriptionRepository, StripeClient stripeClient) { this.accountRepository = accountRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; this.paymentTransactionRepository = paymentTransactionRepository; - this.subscriptionRepository = subscriptionRepository; this.stripeClient = stripeClient; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java index bfc5846ae3..785136a5ff 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java @@ -86,9 +86,15 @@ public VerifiedCaller verifyPresentedCompactToken(String compactJwt) { currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(tokenJti); requireExactCandidate(compactJwt, verified, candidate); return new VerifiedCaller(candidate); - } catch (RuntimeException failure) { - // Do not preserve exception text or causes that could expose credential or parser details. + } catch (CallerUnavailableException + | AccountAsymmetricJwtVerifier.VerificationException + | AccountAsymmetricJwtVerifier.VerificationUnavailableException + | AccountPublicJwksCache.SourceUnavailableException + | AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException refused) { throw unavailable(); + } catch (RuntimeException unexpected) { + // Preserve fault classification without exposing credential, parser or source details. + throw new IllegalStateException("Account gameplay caller verification failed"); } } @@ -181,8 +187,15 @@ private static long numberClaim(Map claims, String field) { } } - private static IllegalStateException unavailable() { - return new IllegalStateException("Account gameplay caller verification is unavailable"); + private static CallerUnavailableException unavailable() { + return new CallerUnavailableException(); + } + + /** Sanitized refusal to provide a verified current LOGIN caller to admission owners. */ + public static final class CallerUnavailableException extends IllegalStateException { + public CallerUnavailableException() { + super("Account gameplay caller verification is unavailable"); + } } /** diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java new file mode 100644 index 0000000000..3e677bfa09 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.time.temporal.ChronoUnit; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.AuthorizedActor; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.AccountAuthenticatedActor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manually composed same-billing-owner cancellation recovery. Current Account identity and fresh + * primary authentication precede the final guarded mutation in its owner transaction. A role, + * caller-supplied actor, expired observation or provider lookup failure cannot clear the hold. No + * HTTP route, global intervention, provider cancellation, registration or activation is added. + */ +public final class AccountHostingSubscriptionTerminalResolutionService { + private final AccountControlUiActorService actors; + private final AccountServiceImpl primaryAuthentication; + private final AccountHostingSubscriptionLifecycleRepository repository; + private final StripeHostingSubscriptionObserver observer; + private final Clock clock; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account owner collaborators are retained privately and never exposed.") + public AccountHostingSubscriptionTerminalResolutionService( + AccountControlUiActorService actors, + AccountServiceImpl primaryAuthentication, + AccountHostingSubscriptionLifecycleRepository repository, + StripeHostingSubscriptionObserver observer, + Clock clock) { + this.actors = Objects.requireNonNull(actors); + this.primaryAuthentication = Objects.requireNonNull(primaryAuthentication); + this.repository = Objects.requireNonNull(repository); + this.observer = Objects.requireNonNull(observer); + this.clock = Objects.requireNonNull(clock); + } + + /** + * The input identifies the exact failed owner operation; it supplies no actor or authorization. + * The final primary-authentication call is purpose-local and immediate, rather than reusing a + * game-creation reauthentication grant or treating a control-ui token's issue time as step-up. + */ + public TransitionResult resolve(String controlUiJwt, String email, String secret, Input input) { + outsideSql(); + Objects.requireNonNull(input, "Exact resolution input is required"); + var prepared = + actors.withCurrentAccount( + controlUiJwt, actor -> repository.prepareTerminalResolution(input.request(actor))); + if (prepared.replayResult() != null) { + // This is an authenticated exact-result read, not another mutation or reauthentication. + return prepared.replayResult(); + } + requireCredentials(email, secret); + outsideSql(); + var observed = observer.observe(prepared.binding()); + outsideSql(); + Attempt attempt = + actors.withCurrentAccount( + controlUiJwt, + actor -> { + requireExactActor(prepared.request(), actor); + try { + return new Attempt( + repository.applyTerminalResolution( + prepared, + observed, + target -> { + requireExactActor(target.request(), actor); + if (!actor.accountId().equals(target.billingOwnerAccountId())) { + throw new FenceRejectedException( + "Only the exact current billing-owner subject may resolve"); + } + requireWritableOwnerTransaction(); + AccountServiceImpl.ControlUiPrimaryIdentity actual; + try { + actual = + primaryAuthentication.authenticateControlUiPrimaryIdentity( + email, secret); + } catch (AuthenticationException denied) { + // The repository invokes this callback before its first mutation. + // Returning the failure from the enclosing transaction preserves real + // failed-login accounting without writing a resolution or consuming + // OTP. + throw new PrimaryAuthenticationDenied(denied.getCode()); + } + if (!actor.accountId().equals(actual.accountId())) { + throw new FenceRejectedException( + "Primary authentication belongs to another Account"); + } + return new AuthorizedActor( + actor.accountId(), + actor.issuanceOperationId(), + actor.tokenHash(), + clock.instant().truncatedTo(ChronoUnit.MICROS)); + }), + null); + } catch (PrimaryAuthenticationDenied denied) { + return new Attempt(null, denied.code); + } + }); + if (attempt.failureCode != null) { + throw new AuthenticationException(attempt.failureCode, "Account reauthentication failed"); + } + return Objects.requireNonNull(attempt.result); + } + + private static void requireExactActor(Request request, AccountAuthenticatedActor actor) { + if (!request.actorAccountId().equals(actor.accountId()) + || !request.controlUiIssuanceOperationId().equals(actor.issuanceOperationId()) + || !request.controlUiTokenHash().equals(actor.tokenHash())) { + throw new FenceRejectedException("Current Account actor differs from the captured operation"); + } + } + + private static void requireCredentials(String email, String secret) { + if (email == null + || email.isBlank() + || email.length() > 254 + || secret == null + || secret.isEmpty() + || secret.length() > 1024) { + throw new IllegalArgumentException("Bounded fresh Account credentials are required"); + } + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction is required"); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Recovery refuses an ambient transaction or synchronization"); + } + } + + /** Exact identifiers and reason only; credentials never enter this value or its digest. */ + public record Input( + UUID resolutionRequestId, + UUID failedRequestId, + UUID creationRequestId, + UUID subscriptionId, + UUID tenantId, + long expectedFailedOperationVersion, + long expectedSubscriptionVersion, + UUID auditEventId, + String auditReason) { + Request request(AccountAuthenticatedActor actor) { + return new Request( + resolutionRequestId, + failedRequestId, + creationRequestId, + subscriptionId, + tenantId, + expectedFailedOperationVersion, + expectedSubscriptionVersion, + actor.accountId(), + actor.issuanceOperationId(), + actor.tokenHash(), + auditEventId, + auditReason); + } + } + + private record Attempt(TransitionResult result, String failureCode) {} + + private static final class PrimaryAuthenticationDenied extends RuntimeException { + private final String code; + + private PrimaryAuthenticationDenied(String code) { + super("Account primary authentication denied"); + this.code = code; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java index 03f9b957c7..5f1c502a44 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.StreamReadFeature; @@ -304,6 +305,10 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity throw unavailable(); } return result; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | TransactionException ownerStateUnavailable) { + throw unavailable(); } catch (RuntimeException ownerStateUnavailable) { if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) { throw unavailable; 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..6308e443e7 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java @@ -0,0 +1,369 @@ +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.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +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 static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtures = + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.withPostgres(POSTGRES); + @TempDir Path directory; + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @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); + // This per-fixture spy counts entry into the real receiver; it replaces no authority. + var receiver = spy(new AccountPlayerAdmissionEntitlementGrpcService(owner, NAMESPACE)); + Server server = + receiver.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()); + verify(receiver).readPlayerAdmissionEntitlement(any(), any()); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) + .isExactlyInstanceOf(StatusRuntimeException.class) + .hasMessage("CANCELLED: Account player-admission entitlement read did not complete") + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.CANCELLED)); + verify(receiver).readPlayerAdmissionEntitlement(any(), any()); + // Retaining valid signature bytes and local custody is insufficient after Account moves. + // The actual caller verifier and receiver classify this currentness loss as UNAVAILABLE. + f.beginPlayerEntitlementLoginRevocation(); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) + .isExactlyInstanceOf(StatusRuntimeException.class) + .hasMessage("UNAVAILABLE: Account player-admission entitlement read did not complete") + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + verify(receiver, times(2)).readPlayerAdmissionEntitlement(any(), any()); + login.close(); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Canonical LOGIN private result is closed"); + verify(receiver, times(2)).readPlayerAdmissionEntitlement(any(), any()); + } 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 new file mode 100644 index 0000000000..6fc7537379 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -0,0 +1,792 @@ +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)) + .isExactlyInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.CANCELLED)); + 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 tenantOperationDemoCapturesCurrentSourceOnActualWritableSerializableConnection() { + Fixture f = fixture(false); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + f.dsl.connection( + connection -> { + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + assertThat(connection.isReadOnly()).isFalse(); + }); + return invocation.callRealMethod(); + }) + .when(f.demos) + .readCurrent(f.tenantId); + var owner = + new AccountTenantOperationEntitlementOwner( + mock(AccountHostingSubscriptionLifecycleService.class), + f.demos, + new DataSourceTransactionManager(f.dataSource), + Clock.fixed(NOW, ZoneOffset.UTC), + NAMESPACE); + var request = + new AccountTenantOperationEntitlementOwner.Request( + f.tenantId, + UUID.randomUUID(), + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service"); + + var evidence = owner.evaluateDemo(request); + + assertThat(evidence.fields()) + .containsEntry("variant", "TENANT_OPERATION") + .containsEntry("sourceKind", "NON_PAID_DEMO") + .containsEntry("tenantId", f.tenantId.toString()) + .containsEntry("requestId", request.requestId().toString()); + } + + @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 blockedAccountSourceReadIsCancelledWithinOwnerTransactionBudget() throws Exception { + Fixture f = fixture(false); + try (Connection blocker = f.dataSource.getConnection()) { + blocker.setAutoCommit(false); + try (var lock = + blocker.prepareStatement( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + lock.setObject(1, f.account.getAccountUuid()); + lock.executeQuery().close(); + // No database-side lock/statement timeout is installed. The actual transaction-aware + // jOOQ connection must propagate the owner's five-second JDBC query timeout. + assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("57014"); + }); + } finally { + blocker.rollback(); + } + } + // Cancellation rolls back the owner transaction and does not damage a later current read. + assertThat(f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN).fields()) + .containsEntry("variant", "PLAYER_ADMISSION"); + } + + @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/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..4d0801bf57 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java @@ -0,0 +1,444 @@ +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.google.protobuf.UnknownFieldSet; +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"); + private static final UUID SECOND_ACTOR = UUID.fromString("88888888-8888-4888-8888-888888888888"); + @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)) + .addActors(actor().setCharacterUuid(SECOND_ACTOR.toString()).setLevel(4)) + .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), + new AccountBootstrapRosterReadClient.Actor(SECOND_ACTOR, "Mara", 4)); + 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 malformedActorFieldsRemainBoundedSourceFailures() throws Exception { + var invalidActors = + List.of( + actor().setLevel(1).setCharacterUuid("source-payload-not-a-uuid").build(), + actor().setLevel(1).clearCharacterUuid().build(), + actor().setLevel(1).setCharacterUuid(new UUID(0L, 0L).toString()).build(), + actor().setLevel(1).clearDisplayName().build(), + actor().setLevel(1).setDisplayName(" ").build(), + actor().setLevel(1).setDisplayName(" Mara").build(), + actor().setLevel(1).setDisplayName("Mara ").build(), + actor().setLevel(1).setDisplayName("M".repeat(101)).build(), + actor().setLevel(1).setDisplayName("Mara\u0007").build(), + actor().setLevel(-1).build()); + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (var invalid : invalidActors) { + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(invalid) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Entity bootstrap discovery actor is malformed") + .hasNoCause(); + } + assertThat(service.calls.get()).isEqualTo(invalidActors.size()); + } + } + + @Test + void actorShapeAndOrderingAreCheckedBeforeSourceUuidParsing() throws Exception { + var unknownFields = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + var invalidActorLists = + List.of( + List.of(actor().setCharacterUuid("source-payload-not-a-uuid").build()), + List.of(actor().setLevel(1).setUnknownFields(unknownFields).build()), + List.of( + actor() + .setLevel(1) + .setCharacterUuid("source-payload-not-a-uuid") + .setUnknownFields(unknownFields) + .build()), + List.of(actor().setLevel(1).build(), actor().setLevel(1).build()), + List.of( + actor().setLevel(1).setCharacterUuid(SECOND_ACTOR.toString()).build(), + actor().setLevel(1).build()), + List.of( + actor().setLevel(1).build(), + actor().setLevel(1).setCharacterUuid("0-source-payload-not-a-uuid").build())); + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (var invalid : invalidActorLists) { + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addAllActors(invalid) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Entity bootstrap discovery actors are duplicated or unordered") + .hasNoCause(); + } + assertThat(service.calls.get()).isEqualTo(invalidActorLists.size()); + } + } + + @Test + void noncanonicalActorUuidRemainsASourceFailure() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (String noncanonical : List.of("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", "7-7-4-8-7")) { + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor().setCharacterUuid(noncanonical).setLevel(1)) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical actor UUID required") + .hasNoCause(); + } + assertThat(service.calls.get()).isEqualTo(2); + } + } + + @Test + void callerInputFailuresRemainArgumentErrorsBeforeTheEntityRead() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (UUID invalid : new UUID[] {null, new UUID(0L, 0L)}) { + assertThatThrownBy(() -> client.read(invalid, ACCOUNT, published())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), invalid, published())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> client.read(UUID.randomUUID(), TENANT, published())) + .isInstanceOf(IllegalArgumentException.class); + var unsupported = published(); + when(unsupported.currentTarget().playableStateScope()).thenReturn("ISOLATED"); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, unsupported)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AccountBootstrapRosterReadClient.Actor(ACTOR, " ", 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(service.calls.get()).isZero(); + } + } + + @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/client/StripeBillingPrerequisiteObserverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java index 42ab782925..4e76953162 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java @@ -86,6 +86,29 @@ void retrievesBothExactObjectsThroughSdkAndReturnsOnlyBoundedImmutableEvidence() Instant.class)); } + @Test + void propagatesCallerTransportOptionsToBothStripeReads() { + ControlledStripeTransport transport = + new ControlledStripeTransport(customerResponse(), paymentMethodResponse()); + RequestOptions options = + RequestOptions.builder() + .setConnectTimeout(1_234) + .setReadTimeout(5_678) + .setMaxNetworkRetries(2) + .build(); + + observer(transport, fixedClock()).observe(expected(), options); + + assertEquals(2, transport.requestOptions().size()); + assertTrue(transport.requestOptions().stream().allMatch(received -> received == options)); + assertEquals(1_234, transport.requestOptions().get(0).getConnectTimeout()); + assertEquals(5_678, transport.requestOptions().get(0).getReadTimeout()); + assertEquals(2, transport.requestOptions().get(0).getMaxNetworkRetries()); + assertEquals(1_234, transport.requestOptions().get(1).getConnectTimeout()); + assertEquals(5_678, transport.requestOptions().get(1).getReadTimeout()); + assertEquals(2, transport.requestOptions().get(1).getMaxNetworkRetries()); + } + @Test void rejectsDeletedMismatchedModeAndWrongCustomerObjectsOrIDs() { assertInvalid( @@ -397,6 +420,7 @@ private static final class ControlledStripeTransport implements StripeResponseGe private final java.util.ArrayList paths = new java.util.ArrayList<>(); private final java.util.ArrayList methods = new java.util.ArrayList<>(); private final java.util.ArrayList> parameters = new java.util.ArrayList<>(); + private final java.util.ArrayList requestOptions = new java.util.ArrayList<>(); private ControlledStripeTransport(String customerResponse, String paymentMethodResponse) { this(customerResponse, paymentMethodResponse, null, null); @@ -434,6 +458,7 @@ public T request( paths.add(requestPath); methods.add(requestMethod); parameters.add(params == null ? Map.of() : Map.copyOf(params)); + requestOptions.add(options); if (requestPath.equals(failurePath)) { throw failure; } @@ -471,5 +496,9 @@ private List methods() { private List> parameters() { return List.copyOf(parameters); } + + private List requestOptions() { + return List.copyOf(requestOptions); + } } } 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/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 29f6e4fa35..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 @@ -3,7 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.time.Clock; @@ -12,11 +14,17 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; import org.jooq.DSLContext; +import org.jooq.Record; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountHostingSubscriptionLifecycleRepositoryTest { @@ -58,6 +66,53 @@ void recoveryOriginIsOnlyRetainedEpisodeHistoryAndMissingHistoryStaysUnresolved( .isEqualTo(original); } + @ParameterizedTest + @ValueSource(longs = {0, 1}) + void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( + long secondsAfterExpiry) { + Instant expiresAt = Instant.parse("2026-11-07T00:00:10Z"); + UUID requestId = UUID.randomUUID(); + UUID attemptId = UUID.randomUUID(); + var controlledIntents = mock(AccountSubscriptionIntentRepository.class); + var controlledRepository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + controlledIntents, + Clock.fixed(expiresAt.plusSeconds(secondsAfterExpiry), ZoneOffset.UTC), + limits(3, 2, 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 creation = mock(AccountSubscriptionCreationRecord.class); + when(creation.requestId()).thenReturn(requestId); + var claim = mock(ProvisioningClaim.class); + when(claim.creation()).thenReturn(creation); + when(claim.attemptId()).thenReturn(attemptId); + 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("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); + 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); + verify(dsl).fetchOne(lockedWorkSql, requestId); + verifyNoMoreInteractions(controlledIntents, dsl); + } + @Test void claimAndSettlementRequireWritableOwnerTransactionBeforeSql() { assertTransactionRefusal(); @@ -67,6 +122,92 @@ void claimAndSettlementRequireWritableOwnerTransactionBeforeSql() { verifyNoInteractions(dsl); } + @Test + void terminalResolutionCaptureAndApplyRequireWritableOwnerTransactionBeforeSql() { + assertThatThrownBy(() -> repository.prepareTerminalResolution(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.applyTerminalResolution(null, null, null)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.prepareTerminalResolution(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.applyTerminalResolution(null, null, null)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @ParameterizedTest + @ValueSource(strings = {"tenant", "subscription", "actor"}) + void terminalResolutionRejectsWrongCallerOrTargetBeforeAnyJournalSqlOrLocks(String changed) { + var request = terminalRequest("Same-owner cancellation resolution"); + var original = mock(AccountSubscriptionCreationRecord.class); + when(original.tenantId()) + .thenReturn("tenant".equals(changed) ? UUID.randomUUID() : request.tenantId()); + when(original.subscriptionId()) + .thenReturn("subscription".equals(changed) ? UUID.randomUUID() : request.subscriptionId()); + when(original.owner()) + .thenReturn( + new AccountSubscriptionCreateRequest.OwnerFence( + "actor".equals(changed) ? UUID.randomUUID() : request.actorAccountId(), + 1, + UUID.randomUUID())); + var controlledIntents = mock(AccountSubscriptionIntentRepository.class); + when(controlledIntents.findCreation(request.creationRequestId())) + .thenReturn(Optional.of(original)); + var controlledRepository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + controlledIntents, + Clock.systemUTC(), + limits(3, 2, 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); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> controlledRepository.prepareTerminalResolution(request)) + .isExactlyInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessage("Exact same-owner terminal lifecycle target rejected"); + + verify(controlledIntents).findCreation(request.creationRequestId()); + verifyNoMoreInteractions(controlledIntents); + verifyNoInteractions(dsl); + } + + @Test + void terminalResolutionReasonIsCanonicalBoundedScalarComparisonData() { + var first = terminalRequest("e\u0301 reason"); + assertThat(first.auditReason()).isEqualTo("é reason"); + assertThat(first.payload()).isNotEmpty(); + for (String invalid : + List.of("", "\u0085\u00a0", "nul\u0000reason", "\ud800", "é".repeat(501))) { + assertThatThrownBy(() -> terminalRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat(terminalRequest("é".repeat(500)).auditReason()).hasSize(500); + } + + private static AccountHostingSubscriptionTerminalResolution.Request terminalRequest( + String reason) { + return new AccountHostingSubscriptionTerminalResolution.Request( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 4, + 3, + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + UUID.randomUUID(), + reason); + } + private void assertTransactionRefusal() { assertThatThrownBy(() -> repository.claim(UUID.randomUUID(), 1, UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) 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/security/AccountTenantOperationEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java new file mode 100644 index 0000000000..491e712c7f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java @@ -0,0 +1,119 @@ +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.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +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 AccountTenantOperationEntitlementWorkloadGuardTest { + private final AccountTenantOperationEntitlementWorkloadGuard guard = + new AccountTenantOperationEntitlementWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsWorldAndMethodCanInstallPrivateAssertion() throws Exception { + var method = + AccountTenantOperationEntitlementReadServiceGrpc.getReadTenantOperationEntitlementMethod(); + assertThat(invoke(method, tls("firemud", "world-management-service"))).isNull(); + assertThatThrownBy(guard::requireAuthenticatedWorldCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "world-management-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", "world-management-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = + AccountTenantOperationEntitlementReadServiceGrpc.getReadTenantOperationEntitlementMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/world-management-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedWorldCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "world-management-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "world-management-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.requireAuthenticatedWorldCaller()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/world-management-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/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java new file mode 100644 index 0000000000..400ad928b7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -0,0 +1,1320 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.intThat; +import static org.mockito.Mockito.clearInvocations; +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.mockConstruction; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLTimeoutException; +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 java.util.stream.Stream; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +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.AccountSubscriptionIntentRepository.FenceRejectedException; +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.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +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.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.RuntimePlayerAdmissionEntitlementGrpcCodec; +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 net.firedevops.firemud.shared.v1.ErrorDetail; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +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(binding.get("playableStateScope")).isEqualTo("SHARED"); + assertThat(binding.get("characterCreationPolicy")).isEqualTo("PRESEEDED_ONLY"); + 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); + } + + @ParameterizedTest + @ValueSource(strings = {"prepare", "current"}) + void paidReadFenceRefusalsBecomeSanitizedUnavailableWithoutDemoFallback(String stage) + 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)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var refusal = new FenceRejectedException("private paid read detail"); + if ("prepare".equals(stage)) { + when(f.hosting.prepareCurrentRead(TENANT)).thenThrow(refusal); + } else { + when(f.hosting.readCurrent(fence, observed)).thenThrow(refusal); + } + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + assertThat(f.transactions.events).endsWith("rollback"); + verifyNoInteractions(f.demos); + if ("prepare".equals(stage)) { + verifyNoInteractions(f.observer, f.targets); + } else { + verify(f.hosting).readCurrent(fence, observed); + } + } + + @ParameterizedTest + @ValueSource(strings = {"prepare", "current"}) + void unrelatedPaidReadFaultsRemainUnexpectedForInternalClassification(String stage) + 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)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var unexpected = new IllegalArgumentException("private unexpected paid read detail"); + if ("prepare".equals(stage)) { + when(f.hosting.prepareCurrentRead(TENANT)).thenThrow(unexpected); + } else { + when(f.hosting.readCurrent(fence, observed)).thenThrow(unexpected); + } + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")).isSameAs(unexpected); + assertThat(f.transactions.events).endsWith("rollback"); + verifyNoInteractions(f.demos); + } + + @Test + void sourceTimeoutReachesJdbcLockingStatementAndRollsBackWithoutReturningEvidence() + throws Exception { + Fixture f = new Fixture(false); + var dataSource = mock(DataSource.class); + var connection = mock(Connection.class); + try (var statement = mock(PreparedStatement.class)) { + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenReturn(true, false); + when(connection.getTransactionIsolation()) + .thenReturn(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE); + when(connection.prepareStatement(anyString())) + .thenAnswer( + invocation -> { + assertThat(invocation.getArgument(0, String.class)).endsWith("for update"); + return statement; + }); + when(statement.execute()).thenThrow(new SQLTimeoutException("Controlled timeout", "57014")); + // The real Spring proxy transfers the remaining transaction budget to jOOQ's JDBC statement. + // The driver is controlled here; physical PostgreSQL cancellation is separate proof. + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + new AccountRepository(dsl), + f.callers, + f.issuances, + f.memberships, + f.scopes, + f.hosting, + f.observer, + f.demos, + f.sources, + f.targets, + new DataSourceTransactionManager(dataSource), + Clock.fixed(NOW, java.time.ZoneOffset.UTC), + "prod"); + + assertThatThrownBy(() -> owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf(DataAccessException.class) + .hasRootCauseExactlyInstanceOf(SQLTimeoutException.class); + verify(statement).execute(); + verify(statement).close(); + verify(statement).setQueryTimeout(intThat(seconds -> seconds > 0 && seconds <= 5)); + verify(connection).rollback(); + verifyNoInteractions( + f.issuances, + f.memberships, + f.scopes, + f.hosting, + f.observer, + f.demos, + f.sources, + f.targets); + } + } + + @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")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + 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"); + } + + @ParameterizedTest + @MethodSource("protectedTargetFailures") + void protectedTargetFailuresKeepTheirClassificationThroughActualOwnerAndReceiver( + String stage, RuntimeException failure, io.grpc.Status.Code expected) throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + // Keep the strict selector stable: the controlled resolver otherwise installs a fresh read. + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + if ("resolve".equals(stage)) { + doThrow(failure).when(f.targets).resolvePublishedRealmAdmissionTarget(any()); + } else { + doThrow(failure).when(f.targets).readPublishedRealmAdmissionOwner(any()); + } + clearInvocations(f.targets); + var direct = assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")); + if (expected == io.grpc.Status.Code.UNAVAILABLE) { + direct + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + } else if (expected == io.grpc.Status.Code.FAILED_PRECONDITION) { + direct + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + } else { + direct.isSameAs(failure); + } + assertReceiverRefusal(f, expected); + verify(f.targets, times(2)).resolvePublishedRealmAdmissionTarget(f.request.target()); + if ("strict".equals(stage)) { + verify(f.targets, times(2)).readPublishedRealmAdmissionOwner(resolved.strictSelector()); + } else { + verify(f.targets, never()).readPublishedRealmAdmissionOwner(any()); + } + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @SuppressWarnings("unchecked") + private static void assertReceiverRefusal(Fixture f, io.grpc.Status.Code expected) + throws Exception { + String token = "controlled-token.payload.signature"; + var caller = f.callers.verifyPresentedCompactToken("controlled-token"); + when(f.callers.verifyPresentedCompactToken(token)).thenReturn(caller); + try (var guards = + mockConstruction( + AccountPlayerAdmissionEntitlementWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedGameSessionCaller()).thenReturn(PEER))) { + var receiver = new AccountPlayerAdmissionEntitlementGrpcService(f.owner, "prod"); + StreamObserver observer = mock(StreamObserver.class); + receiver.readPlayerAdmissionEntitlement( + RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest( + new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + f.request.target(), f.request.connectScopeId()), + token), + observer); + var refused = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(refused.capture()); + var status = StatusProto.fromThrowable(refused.getValue()); + assertThat(status).isNotNull(); + assertThat(status.getCode()).isEqualTo(expected.value()); + String message = "Player-admission entitlement evidence is unavailable"; + assertThat(status.getMessage()).isEqualTo(message); + assertThat(status.getDetailsCount()).isOne(); + assertThat(status.getDetails(0).unpack(ErrorDetail.class)) + .isEqualTo(ErrorDetail.newBuilder().setCode(expected.name()).setMessage(message).build()); + assertThat(refused.getValue()).hasNoCause(); + assertThat(status.toString()) + .doesNotContain(token, f.scope.connectScopeId(), "private target detail"); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + } + + private static Stream protectedTargetFailures() { + return Stream.of("resolve", "strict") + .flatMap( + stage -> { + Stream outages = + Stream.of( + new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( + new IllegalStateException("private target detail")), + io.grpc.Status.UNAVAILABLE + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.DEADLINE_EXCEEDED + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.CANCELLED + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.ABORTED + .withDescription("private target detail") + .asRuntimeException()); + Stream unexpected = + Stream.of( + io.grpc.Status.INVALID_ARGUMENT + .withDescription("private target detail") + .asRuntimeException(), + new IllegalArgumentException("private target detail"), + new IllegalStateException( + "Game Session returned invalid current target evidence", + new IllegalArgumentException("private target detail")), + new NullPointerException("private target detail")); + return Stream.concat( + Stream.concat( + outages.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.UNAVAILABLE)), + Stream.of( + Arguments.of( + stage, + io.grpc.Status.FAILED_PRECONDITION + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.Code.FAILED_PRECONDITION))), + unexpected.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.INTERNAL))); + }); + } + + @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")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + @ParameterizedTest + @ValueSource(strings = {"resolved-selector", "strict-selector", "strict-target", "current-scope"}) + void changedProtectedTargetComparisonsRemainPreconditionsThroughOwnerAndReceiver(String change) + throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + var read = f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + clearInvocations(f.targets); + switch (change) { + case "resolved-selector" -> + when(resolved.selector()) + .thenReturn( + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class)); + case "strict-selector" -> + when(read.selector()) + .thenReturn(mock(CanonicalGameplayRosterOwnerReadEvidence.Request.class)); + case "strict-target" -> + when(read.currentTarget()) + .thenReturn(mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class)); + case "current-scope" -> + when(resolved.currentTarget().playableStateScope()).thenReturn("ISOLATED"); + default -> throw new AssertionError("Unknown controlled target change"); + } + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + verify(f.targets, times(2)).resolvePublishedRealmAdmissionTarget(f.request.target()); + if (change.startsWith("strict-")) { + verify(f.targets, times(2)).readPublishedRealmAdmissionOwner(resolved.strictSelector()); + } else { + verify(f.targets, never()).readPublishedRealmAdmissionOwner(any()); + } + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"PLAYER_CREATED", "unknown", ""}) + void unsupportedCurrentPolicyCannotBecomePreseededPlayerEvidence(String policy) throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + when(resolved.currentTarget().characterCreationPolicy()).thenReturn(policy); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.never()) + .readPublishedRealmAdmissionOwner(any()); + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @Test + void isolatedRetainedScopeFailsBeforeProtectedTargetOrEntitlementCapture() throws Exception { + Fixture f = new Fixture(false, "ISOLATED"); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "rollback", "begin", "rollback"); + } + + @Test + void protectedReadCannotReplaceSupportedPolicyBeforeEvidenceCapture() throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + var original = f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + when(f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())) + .thenAnswer( + invocation -> { + when(original.currentTarget().characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + return original; + }); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @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; + 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; + private final AccountPlayerAdmissionEntitlementOwner owner; + + private Fixture(boolean exists) throws Exception { + this(exists, "SHARED"); + } + + private Fixture(boolean exists, String stateScope) throws Exception { + scope = + new CanonicalJoinScopeV2( + "private-bearer-" + UUID.randomUUID(), + ACCOUNT, + TENANT, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + stateScope, + UUID.randomUUID(), + 7, + 3, + NOW.minusSeconds(20).toString(), + NOW.plusSeconds(60).toString()); + request = + new Request( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + ACCOUNT, + "prod", + TENANT, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + "SHARED", + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()), + scope.connectScopeId(), + PEER); + 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(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + } + 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/AccountPublicBootstrapWorldsOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java index f66f27186a..fc6bdb624c 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 @@ -89,6 +89,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(); @@ -386,6 +403,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", @@ -425,7 +452,7 @@ private static Target target( OwnerProofOutcome.COMMITTED, false, NOW, - "PRESEEDED_ONLY"); + creationPolicy); } private static Account account(long id) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java new file mode 100644 index 0000000000..c2c35caf09 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java @@ -0,0 +1,92 @@ +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.anyString; +import static org.mockito.ArgumentMatchers.intThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLTimeoutException; +import java.time.Clock; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantOperationEntitlementOwnerTest { + @Test + void demoUsesIndependentWritableSerializableTransactionAndPropagatesFiveSecondJdbcBudget() + throws Exception { + var dataSource = mock(DataSource.class); + var connection = mock(Connection.class); + var transactions = spy(new DataSourceTransactionManager(dataSource)); + var demos = mock(AccountDemoTenantEntitlementRepository.class); + var hosting = mock(AccountHostingSubscriptionLifecycleService.class); + UUID tenantId = UUID.randomUUID(); + var request = + new AccountTenantOperationEntitlementOwner.Request( + tenantId, UUID.randomUUID(), "spiffe://firemud/ns/prod/sa/world-management-service"); + try (var statement = mock(PreparedStatement.class)) { + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenReturn(true, false); + when(connection.getTransactionIsolation()) + .thenReturn(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE); + when(connection.prepareStatement(anyString())).thenReturn(statement); + when(statement.execute()).thenThrow(new SQLTimeoutException("Controlled timeout", "57014")); + // The actual Spring proxy carries the transaction timeout to jOOQ's JDBC statement. + // This driver is controlled; the PostgreSQL suite proves physical connection isolation. + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + when(demos.readCurrent(tenantId)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + dsl.connection( + current -> + assertThat(current.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + dsl.execute("SELECT 1"); + throw new AssertionError("The controlled source statement must time out"); + }); + var owner = + new AccountTenantOperationEntitlementOwner( + hosting, demos, transactions, Clock.systemUTC(), "prod"); + + assertThatThrownBy(() -> owner.evaluateDemo(request)) + .isExactlyInstanceOf(DataAccessException.class) + .hasRootCauseExactlyInstanceOf(SQLTimeoutException.class); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getValue().isReadOnly()).isFalse(); + assertThat(definition.getValue().getTimeout()).isEqualTo(5); + verify(connection).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + verify(statement).setQueryTimeout(intThat(seconds -> seconds > 0 && seconds <= 5)); + verify(connection).rollback(); + verifyNoInteractions(hosting); + } + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } +} 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..a6b0fc81aa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -0,0 +1,332 @@ +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.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Handler classifications use a controlled guard, not a claim of authenticated TLS custody. */ +class AccountPlayerAdmissionEntitlementGrpcServiceTest { + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String JWT = "private-token.payload.signature"; + private static final String SCOPE = "private-scope"; + private static final String SECRET = "private-source-internal-identifier"; + private static final String MESSAGE = "Player-admission entitlement evidence is unavailable"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + @SuppressWarnings("unchecked") + void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() throws Exception { + 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); + assertRefusal(observer, Status.Code.UNAUTHENTICATED); + } + verifyNoInteractions(owner); + } + + @ParameterizedTest + @MethodSource("ownerFailures") + void ownerFailuresRetainExactAvailabilityClassificationWithoutSourceDetails( + RuntimeException cause, Status.Code expected) throws Exception { + try (var f = new AuthenticatedFixture()) { + when(f.owner.evaluate(any(), any())).thenThrow(cause); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + assertRefusal(f.observer, expected); + verify(f.owner).evaluate(sourceRequest("prod"), JWT); + } + } + + private static Stream ownerFailures() { + return Stream.of( + org.junit.jupiter.params.provider.Arguments.of( + new AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException(), + Status.Code.FAILED_PRECONDITION), + org.junit.jupiter.params.provider.Arguments.of( + new AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException(), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new AccountGameplayAdmissionCallerVerifier.CallerUnavailableException(), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException( + new IllegalStateException(SECRET)), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new DemoTenantEntitlementException( + DemoTenantEntitlementException.Code.ENTITLEMENT_UNAVAILABLE, SECRET), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new org.jooq.exception.DataAccessException(SECRET), Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new org.springframework.dao.DataAccessResourceFailureException(SECRET), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new org.springframework.transaction.CannotCreateTransactionException(SECRET), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new IllegalStateException("Account gameplay caller verification failed"), + Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new IllegalStateException("ENTITLEMENT_UNAVAILABLE: " + SECRET), Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new IllegalArgumentException(SECRET), Status.Code.INTERNAL), + // Only the protected-target owner boundary may translate its transport failures. + org.junit.jupiter.params.provider.Arguments.of( + Status.UNAVAILABLE.withDescription(SECRET).asRuntimeException(), Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + Status.FAILED_PRECONDITION.withDescription(SECRET).asRuntimeException(), + Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( + new IllegalStateException(SECRET)), + Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new NullPointerException(SECRET), Status.Code.INTERNAL)); + } + + @Test + void authenticatedMalformedAndWrongNamespaceRequestsNeverReachOwner() throws Exception { + try (var f = new AuthenticatedFixture()) { + f.service.readPlayerAdmissionEntitlement(null, f.observer); + assertRefusal(f.observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(f.owner); + } + try (var f = new AuthenticatedFixture()) { + f.service.readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest.getDefaultInstance(), f.observer); + assertRefusal(f.observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(f.owner); + } + try (var f = new AuthenticatedFixture()) { + f.service.readPlayerAdmissionEntitlement(wire("other"), f.observer); + assertRefusal(f.observer, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(f.owner); + } + } + + @Test + void ambientTransactionAndSynchronizationRefuseBeforeOwnerOrParsing() throws Exception { + try (var f = new AuthenticatedFixture()) { + TransactionSynchronizationManager.setActualTransactionActive(true); + f.service.readPlayerAdmissionEntitlement(null, f.observer); + assertRefusal(f.observer, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.owner); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + try (var f = new AuthenticatedFixture()) { + TransactionSynchronizationManager.initSynchronization(); + f.service.readPlayerAdmissionEntitlement(null, f.observer); + assertRefusal(f.observer, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.owner); + } + } + + @Test + void successfulOwnerValueUsesExactCallerCredentialAndClosedResponseBinding() throws Exception { + try (var f = new AuthenticatedFixture()) { + var evidence = evidence(); + when(f.owner.evaluate(any(), any())).thenReturn(evidence); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + var response = ArgumentCaptor.forClass(ReadPlayerAdmissionEntitlementResponse.class); + verify(f.observer).onNext(response.capture()); + assertThat(response.getValue()) + .isEqualTo( + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request("prod"), evidence)); + assertThat(response.getValue().toString()).doesNotContain(JWT); + verify(f.owner).evaluate(sourceRequest("prod"), JWT); + verify(f.observer).onCompleted(); + verify(f.observer, never()).onError(any()); + } + } + + @Test + void responseBindingOrCodecFaultIsInternalAndNeverEmitsEvidence() throws Exception { + try (var f = new AuthenticatedFixture()) { + var evidence = evidence(); + when(evidence.fields()).thenReturn(Map.of()); + when(f.owner.evaluate(any(), any())).thenReturn(evidence); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + assertRefusal(f.observer, Status.Code.INTERNAL); + } + } + + @Test + void responseCallbackFaultIsInternalWithoutCompletionOrPrivateDetails() throws Exception { + try (var f = new AuthenticatedFixture()) { + var evidence = evidence(); + when(f.owner.evaluate(any(), any())).thenReturn(evidence); + doThrow(new IllegalStateException(SECRET)).when(f.observer).onNext(any()); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + assertStructuredFailure(f.observer, Status.Code.INTERNAL); + verify(f.observer, never()).onCompleted(); + } + } + + private static void assertRefusal( + StreamObserver observer, Status.Code expected) + throws Exception { + assertStructuredFailure(observer, expected); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + + private static void assertStructuredFailure( + StreamObserver observer, Status.Code expected) + throws Exception { + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()).isEqualTo(expected); + var status = StatusProto.fromThrowable(failure.getValue()); + assertThat(status).isNotNull(); + assertThat(status.getCode()).isEqualTo(expected.value()); + assertThat(status.getMessage()).isEqualTo(MESSAGE); + assertThat(status.getDetailsCount()).isOne(); + var detail = status.getDetails(0).unpack(ErrorDetail.class); + assertThat(detail) + .isEqualTo(ErrorDetail.newBuilder().setCode(expected.name()).setMessage(MESSAGE).build()); + assertThat(status.getSerializedSize()).isLessThan(256); + assertThat(status.toString()).doesNotContain(JWT, SCOPE, SECRET, "private-token"); + assertThat(failure.getValue().getCause()).isNull(); + } + + private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request(String namespace) { + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + new RetainedTargetSelector( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + namespace, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "tenant", + "world", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "production", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "SHARED", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + 7, + 3), + SCOPE); + } + + private static ReadPlayerAdmissionEntitlementRequest wire(String namespace) { + return RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request(namespace), JWT); + } + + private static AccountPlayerAdmissionEntitlementOwner.Request sourceRequest(String namespace) { + return new AccountPlayerAdmissionEntitlementOwner.Request( + request(namespace).target(), SCOPE, PEER); + } + + /** The owner unit tests prove canonical content; this double isolates response forwarding. */ + private static RuntimePlayerAdmissionEntitlementEvidence evidence() { + var request = request("prod"); + var target = request.target(); + Map binding = new LinkedHashMap<>(); + binding.put("targetNamespace", "prod"); + binding.put("tenantId", target.tenantId().toString()); + binding.put("tenantSlug", target.tenantSlug()); + binding.put("worldSlug", target.worldSlug()); + binding.put("realmId", target.realmId().toString()); + binding.put("realmSlug", target.realmSlug()); + binding.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + binding.put("playableStateScope", target.playableStateScope()); + binding.put("gameInstanceId", target.gameInstanceId().toString()); + binding.put("catalogRevision", "7"); + binding.put("pointerVersion", "3"); + var evidence = mock(RuntimePlayerAdmissionEntitlementEvidence.class); + when(evidence.fields()) + .thenReturn( + Map.of( + "callerAccountId", + target.accountId().toString(), + "tenantId", + target.tenantId().toString(), + "requestId", + target.readRequestId().toString(), + "callerWorkload", + PEER, + "verifiedConnectScopeId", + SCOPE, + "target", + binding)); + when(evidence.canonicalBytes()) + .thenReturn("controlled-owner-value".getBytes(StandardCharsets.UTF_8)); + return evidence; + } + + private static final class AuthenticatedFixture implements AutoCloseable { + private final MockedConstruction guards; + private final AccountPlayerAdmissionEntitlementOwner owner = + mock(AccountPlayerAdmissionEntitlementOwner.class); + private final AccountPlayerAdmissionEntitlementGrpcService service; + + @SuppressWarnings("unchecked") + private final StreamObserver observer = + mock(StreamObserver.class); + + private AuthenticatedFixture() { + guards = + mockConstruction( + AccountPlayerAdmissionEntitlementWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedGameSessionCaller()).thenReturn(PEER)); + service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); + } + + @Override + public void close() { + guards.close(); + } + } +} 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 ff8ba33dbe..ec8ae17445 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 @@ -3995,24 +3995,6 @@ void getTenantMembershipForRuntimeRejectsMissingAccount() { () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); } - @Test - void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(!dto.membershipExists()); - assertTrue(!dto.gameplayAdmissionAllowed()); - } - @ParameterizedTest @CsvSource({ "active,true,true", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java index a6452f228b..ae2986a85d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java @@ -11,7 +11,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -22,7 +21,6 @@ class PaymentServiceImplTest { @Mock private AccountRepository accountRepository; @Mock private AccountTenantMembershipRepository membershipRepository; @Mock private PaymentTransactionRepository txRepo; - @Mock private SubscriptionRepository subRepo; @Mock private StripeClient stripeClient; private PaymentServiceImpl service; @@ -30,9 +28,7 @@ class PaymentServiceImplTest { @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - service = - new PaymentServiceImpl( - accountRepository, membershipRepository, txRepo, subRepo, stripeClient); + service = new PaymentServiceImpl(accountRepository, membershipRepository, txRepo, stripeClient); } @Test @@ -71,7 +67,7 @@ void createSubscriptionFailsBeforeCheckingMembershipOrMutatingAnything() { assertThrows(IllegalStateException.class, () -> service.createSubscription(2L, 1L, "plan")); assertEquals("Subscription creation is unavailable", error.getMessage()); - verifyNoInteractions(accountRepository, membershipRepository, txRepo, subRepo, stripeClient); + verifyNoInteractions(accountRepository, membershipRepository, txRepo, stripeClient); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java index d03c64a286..9283b0e399 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java @@ -268,9 +268,9 @@ void rejectsCandidateHashIdentityAndAuthorityMismatchWithoutRetainingCredentialD when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) .thenReturn(mismatchedCandidate); - IllegalStateException failure = + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException failure = assertThrows( - IllegalStateException.class, + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException.class, () -> fixture.verifier.verifyPresentedCompactToken(compactJwt)); assertNull(failure.getCause()); @@ -280,14 +280,69 @@ void rejectsCandidateHashIdentityAndAuthorityMismatchWithoutRetainingCredentialD } } + @Test + void currentIssuanceRefusalUsesSanitizedTypedCallerUnavailableFailure() throws Exception { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenThrow(new AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException()); + + assertUnavailable(fixture.verifier, compactJwt); + + verify(fixture.currentIssuanceOwner).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void actualTrustedJwksOutagesRemainTypedBeforePinningAndDuringKeyLoading() throws Exception { + for (boolean alreadyPinned : List.of(false, true)) { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + if (alreadyPinned) { + fixture.trustedJwksSource.sourceIdentity(); + } + when(fixture.configMapClient.observe()) + .thenThrow(new AccountJwtJwksConfigMapClient.ApiFailureException(503)); + + assertUnavailable(fixture.verifier, compactJwt); + + verifyNoInteractions(fixture.currentIssuanceOwner); + } + } + + @Test + void unexpectedTrustedSourceAndCurrentnessFaultsRemainSanitizedInternalFailures() + throws Exception { + for (boolean sourceFault : List.of(false, true)) { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + var unexpected = new NullPointerException("private unexpected detail: " + compactJwt); + if (sourceFault) { + when(fixture.configMapClient.observe()).thenThrow(unexpected); + } else { + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenThrow(unexpected); + } + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> fixture.verifier.verifyPresentedCompactToken(compactJwt)); + + assertEquals(IllegalStateException.class, failure.getClass()); + assertEquals("Account gameplay caller verification failed", failure.getMessage()); + assertNull(failure.getCause()); + assertFalse(failure.toString().contains(compactJwt)); + } + } + @Test void refusesAmbientTransactionBeforeTrustedSourceOrCurrentnessReads() { Fixture fixture = new Fixture(); TransactionSynchronizationManager.setActualTransactionActive(true); - IllegalStateException failure = + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException failure = assertThrows( - IllegalStateException.class, + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException.class, () -> fixture.verifier.verifyPresentedCompactToken("credential-not-retained")); assertNull(failure.getCause()); @@ -301,9 +356,10 @@ void refusesAmbientTransactionBeforeTrustedSourceOrCurrentnessReads() { private static void assertUnavailable( AccountGameplayAdmissionCallerVerifier verifier, String compactJwt) { - IllegalStateException failure = + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException failure = assertThrows( - IllegalStateException.class, () -> verifier.verifyPresentedCompactToken(compactJwt)); + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException.class, + () -> verifier.verifyPresentedCompactToken(compactJwt)); assertNull(failure.getCause()); assertEquals("Account gameplay caller verification is unavailable", failure.getMessage()); assertFalse(failure.toString().contains(compactJwt)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java new file mode 100644 index 0000000000..21d89cd499 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java @@ -0,0 +1,486 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ExpectedBinding; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ResolutionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Authorization; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.AuthorizedActor; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.LockedTarget; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.AccountAuthenticatedActor; +import org.junit.jupiter.api.AfterEach; +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.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountHostingSubscriptionTerminalResolutionServiceTest { + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID ISSUANCE = UUID.randomUUID(); + private static final String TOKEN_HASH = "a".repeat(64); + private static final UUID RESOLUTION = UUID.randomUUID(); + private static final UUID FAILED_REQUEST = UUID.randomUUID(); + private static final UUID CREATION = UUID.randomUUID(); + private static final UUID SUBSCRIPTION = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID AUDIT = UUID.randomUUID(); + private static final String CONTROL_UI_JWT = "controlled-test-jwt"; + private static final String EMAIL = "account@example.test"; + private static final String SECRET = "test-primary-secret"; + private static final Instant NOW = Instant.parse("2026-11-03T00:00:00Z"); + + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void providerReadSeparatesCurrentActorCaptureFromFinalPrimaryAuthenticationAndMutation() { + Fixture fixture = new Fixture(); + AccountAuthenticatedActor actor = actor(ACCOUNT, ISSUANCE, TOKEN_HASH); + fixture.currentActors(actor, actor); + fixture.prepare(null); + fixture.observeOutsideOwnerTransaction(); + fixture.applyAfterAuthorization(ACCOUNT); + fixture.primaryAuthenticatesAs(ACCOUNT); + + TransitionResult result = fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input()); + + assertThat(result).isSameAs(fixture.committed); + assertThat(fixture.events) + .containsSubsequence( + "prepare", + "provider-read", + "current-actor-2", + "apply", + "primary-authentication", + "resolution-write"); + assertThat(fixture.commits.commits).isEqualTo(2); + assertThat(fixture.resolutionWrites.get()).isEqualTo(1); + Request request = fixture.preparedRequest.get(); + assertThat(request.actorAccountId()).isEqualTo(ACCOUNT); + assertThat(request.controlUiIssuanceOperationId()).isEqualTo(ISSUANCE); + assertThat(request.controlUiTokenHash()).isEqualTo(TOKEN_HASH); + AuthorizedActor authorized = fixture.authorizedActor.get(); + assertThat(authorized.actorAccountId()).isEqualTo(ACCOUNT); + assertThat(authorized.controlUiIssuanceOperationId()).isEqualTo(ISSUANCE); + assertThat(authorized.controlUiTokenHash()).isEqualTo(TOKEN_HASH); + assertThat(authorized.authenticatedAt()).isEqualTo(NOW); + } + + @Test + void changedCurrentAccountIssuanceOrTokenSourceCannotReachResolutionAuthorization() { + List mismatches = + List.of( + actor(UUID.randomUUID(), ISSUANCE, TOKEN_HASH), + actor(ACCOUNT, UUID.randomUUID(), TOKEN_HASH), + actor(ACCOUNT, ISSUANCE, "b".repeat(64))); + + for (AccountAuthenticatedActor changedActor : mismatches) { + Fixture fixture = new Fixture(); + fixture.currentActors(actor(ACCOUNT, ISSUANCE, TOKEN_HASH), changedActor); + fixture.prepare(null); + fixture.observeOutsideOwnerTransaction(); + fixture.applyAfterAuthorization(ACCOUNT); + + Throwable failure = + catchThrowable(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())); + + assertThat(failure).isInstanceOf(FenceRejectedException.class); + assertThat(fixture.events).contains("provider-read", "current-actor-2"); + assertThat(fixture.resolutionWrites).hasValue(0); + verify(fixture.repository, never()) + .applyTerminalResolution( + any(ResolutionPreparation.class), any(), any(Authorization.class)); + verifyNoInteractions(fixture.primaryAuthentication); + } + } + + @Test + void unavailableCurrentActorStopsBeforeProviderOrFinalAuthorization() { + Fixture beforeProvider = new Fixture(); + beforeProvider.currentActorUnavailableOnFirstCall(); + assertThatThrownBy(() -> beforeProvider.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions( + beforeProvider.repository, beforeProvider.observer, beforeProvider.primaryAuthentication); + + Fixture afterProvider = new Fixture(); + afterProvider.currentActorAvailableThenUnavailable(actor(ACCOUNT, ISSUANCE, TOKEN_HASH)); + afterProvider.prepare(null); + afterProvider.observeOutsideOwnerTransaction(); + afterProvider.applyAfterAuthorization(ACCOUNT); + assertThatThrownBy(() -> afterProvider.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class); + assertThat(afterProvider.events) + .containsSubsequence("provider-read", "final-actor-unavailable"); + assertThat(afterProvider.resolutionWrites).hasValue(0); + verifyNoInteractions(afterProvider.primaryAuthentication); + verify(afterProvider.repository, never()) + .applyTerminalResolution(any(ResolutionPreparation.class), any(), any(Authorization.class)); + } + + @Test + void wrongLockedBillingOwnerOrPrimaryAccountCannotWriteResolution() { + Fixture wrongOwner = new Fixture(); + AccountAuthenticatedActor actor = actor(ACCOUNT, ISSUANCE, TOKEN_HASH); + wrongOwner.currentActors(actor, actor); + wrongOwner.prepare(null); + wrongOwner.observeOutsideOwnerTransaction(); + wrongOwner.applyAfterAuthorization(UUID.randomUUID()); + wrongOwner.primaryAuthenticatesAs(ACCOUNT); + + assertThatThrownBy(() -> wrongOwner.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(FenceRejectedException.class) + .hasMessageContaining("billing-owner"); + assertThat(wrongOwner.resolutionWrites).hasValue(0); + verifyNoInteractions(wrongOwner.primaryAuthentication); + + Fixture wrongPrimaryAccount = new Fixture(); + wrongPrimaryAccount.currentActors(actor, actor); + wrongPrimaryAccount.prepare(null); + wrongPrimaryAccount.observeOutsideOwnerTransaction(); + wrongPrimaryAccount.applyAfterAuthorization(ACCOUNT); + wrongPrimaryAccount.primaryAuthenticatesAs(UUID.randomUUID()); + + assertThatThrownBy( + () -> wrongPrimaryAccount.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(FenceRejectedException.class) + .hasMessageContaining("another Account"); + assertThat(wrongPrimaryAccount.resolutionWrites).hasValue(0); + assertThat(wrongPrimaryAccount.events).contains("primary-authentication"); + } + + @Test + void deniedPrimaryAuthenticationCommitsFailureAccountingBeforeGenericErrorReturns() { + Fixture fixture = new Fixture(); + AccountAuthenticatedActor actor = actor(ACCOUNT, ISSUANCE, TOKEN_HASH); + fixture.currentActors(actor, actor); + fixture.prepare(null); + fixture.observeOutsideOwnerTransaction(); + fixture.applyAfterAuthorization(ACCOUNT); + fixture.primaryAuthenticationDenied(); + + Throwable failure = + catchThrowable(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())); + + assertThat(failure).isInstanceOf(AuthenticationException.class); + AuthenticationException error = (AuthenticationException) failure; + assertThat(error.getCode()).isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS); + assertThat(error).hasMessage("Account reauthentication failed"); + assertThat(error.getCause()).isNull(); + assertThat(error.toString()).doesNotContain(EMAIL, SECRET); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.failedAttemptCommitted).isTrue(); + assertThat(fixture.commits.commits).isEqualTo(2); + assertThat(fixture.resolutionWrites).hasValue(0); + assertThat(fixture.events) + .containsSubsequence( + "primary-authentication", "current-account-return-2", "failed-login-attempt-committed"); + } + + @Test + void exactAuthenticatedReplayReturnsWithoutAnotherProviderReadOrPrimaryAuthentication() { + Fixture fixture = new Fixture(); + fixture.currentActors(actor(ACCOUNT, ISSUANCE, TOKEN_HASH)); + TransitionResult replay = new TransitionResult(RESOLUTION, Outcome.COMMITTED, 12L, null); + fixture.prepare(replay); + + TransitionResult result = fixture.service.resolve(CONTROL_UI_JWT, null, null, input()); + + assertThat(result).isSameAs(replay); + Request request = fixture.preparedRequest.get(); + assertThat(request.actorAccountId()).isEqualTo(ACCOUNT); + assertThat(request.controlUiIssuanceOperationId()).isEqualTo(ISSUANCE); + assertThat(request.controlUiTokenHash()).isEqualTo(TOKEN_HASH); + assertThat(fixture.commits.commits).isEqualTo(1); + verifyNoInteractions(fixture.observer, fixture.primaryAuthentication); + verify(fixture.repository, never()) + .applyTerminalResolution(any(ResolutionPreparation.class), any(), any(Authorization.class)); + } + + @Test + void ambientTransactionOrSynchronizationRefusesBeforeAnyCollaborator() { + Fixture fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verifyNoInteractions( + fixture.actors, fixture.repository, fixture.observer, fixture.primaryAuthentication); + } + + private static AccountHostingSubscriptionTerminalResolutionService.Input input() { + return new AccountHostingSubscriptionTerminalResolutionService.Input( + RESOLUTION, + FAILED_REQUEST, + CREATION, + SUBSCRIPTION, + TENANT, + 7L, + 11L, + AUDIT, + "operator-confirmed provider cancellation"); + } + + private static AccountAuthenticatedActor actor( + UUID accountId, UUID issuanceId, String tokenHash) { + AccountAuthenticatedActor actor = mock(AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(accountId); + when(actor.issuanceOperationId()).thenReturn(issuanceId); + when(actor.tokenHash()).thenReturn(tokenHash); + return actor; + } + + private static AccountServiceImpl.ControlUiPrimaryIdentity primaryIdentity(UUID accountId) { + AccountServiceImpl.ControlUiPrimaryIdentity identity = + mock(AccountServiceImpl.ControlUiPrimaryIdentity.class); + when(identity.accountId()).thenReturn(accountId); + return identity; + } + + private static final class Fixture { + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final AccountServiceImpl primaryAuthentication = mock(AccountServiceImpl.class); + private final AccountHostingSubscriptionLifecycleRepository repository = + mock(AccountHostingSubscriptionLifecycleRepository.class); + private final StripeHostingSubscriptionObserver observer = + mock(StripeHostingSubscriptionObserver.class); + private final LocalTransactions commits = new LocalTransactions(); + private final TransactionTemplate transaction = new TransactionTemplate(commits); + private final ResolutionPreparation preparation = mock(ResolutionPreparation.class); + private final ExpectedBinding binding = + new ExpectedBinding( + "sub_provider_exact", + SUBSCRIPTION, + "cus_provider_exact", + "pm_provider_exact", + "price_hosting_exact", + 1L, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + CREATION, + true); + private final ObservedSubscription observed = mock(ObservedSubscription.class); + private final TransitionResult committed = + new TransitionResult(RESOLUTION, Outcome.COMMITTED, 12L, null); + private final AtomicReference preparedRequest = new AtomicReference<>(); + private final AtomicReference authorizedActor = new AtomicReference<>(); + private final AtomicInteger resolutionWrites = new AtomicInteger(); + private final List events = new ArrayList<>(); + private boolean failedAttemptCommitted; + private final AccountHostingSubscriptionTerminalResolutionService service = + new AccountHostingSubscriptionTerminalResolutionService( + actors, primaryAuthentication, repository, observer, Clock.fixed(NOW, ZoneOffset.UTC)); + + private void currentActors(AccountAuthenticatedActor... currentActors) { + AtomicInteger calls = new AtomicInteger(); + doAnswer( + invocation -> { + int index = calls.getAndIncrement(); + if (index >= currentActors.length) { + throw new IllegalStateException("Unexpected current Account actor request"); + } + int ordinal = index + 1; + events.add("current-actor-" + ordinal); + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(1); + return inOwnerTransaction( + () -> { + Object result = action.apply(currentActors[index]); + events.add("current-account-return-" + ordinal); + return result; + }); + }) + .when(actors) + .withCurrentAccount(eq(CONTROL_UI_JWT), any()); + } + + private void currentActorUnavailableOnFirstCall() { + doAnswer( + invocation -> { + events.add("initial-actor-unavailable"); + throw new IllegalStateException("current Account actor unavailable"); + }) + .when(actors) + .withCurrentAccount(eq(CONTROL_UI_JWT), any()); + } + + private void currentActorAvailableThenUnavailable(AccountAuthenticatedActor currentActor) { + AtomicInteger calls = new AtomicInteger(); + doAnswer( + invocation -> { + if (calls.getAndIncrement() > 0) { + events.add("final-actor-unavailable"); + throw new IllegalStateException("final current Account actor unavailable"); + } + events.add("current-actor-1"); + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(1); + return inOwnerTransaction(() -> action.apply(currentActor)); + }) + .when(actors) + .withCurrentAccount(eq(CONTROL_UI_JWT), any()); + } + + private void prepare(TransitionResult replay) { + when(preparation.binding()).thenReturn(binding); + when(preparation.replayResult()).thenReturn(replay); + doAnswer(invocation -> preparedRequest.get()).when(preparation).request(); + doAnswer( + invocation -> { + assertWritableOwnerTransaction(); + Request request = invocation.getArgument(0); + preparedRequest.set(request); + events.add("prepare"); + doAnswer(ignored -> request).when(preparation).request(); + return preparation; + }) + .when(repository) + .prepareTerminalResolution(any(Request.class)); + } + + private void observeOutsideOwnerTransaction() { + doAnswer( + invocation -> { + assertNoTransactionOrSynchronization(); + assertThat(invocation.getArgument(0, ExpectedBinding.class)).isEqualTo(binding); + events.add("provider-read"); + return observed; + }) + .when(observer) + .observe(any(ExpectedBinding.class)); + } + + private void applyAfterAuthorization(UUID billingOwner) { + doAnswer( + invocation -> { + assertWritableOwnerTransaction(); + events.add("apply"); + ResolutionPreparation prepared = invocation.getArgument(0); + Authorization authorization = invocation.getArgument(2); + AuthorizedActor authorized = + authorization.requireAuthorized( + new LockedTarget(prepared.request(), billingOwner, 11L)); + authorizedActor.set(authorized); + resolutionWrites.incrementAndGet(); + events.add("resolution-write"); + return committed; + }) + .when(repository) + .applyTerminalResolution( + any(ResolutionPreparation.class), any(), any(Authorization.class)); + } + + private void primaryAuthenticatesAs(UUID accountId) { + AccountServiceImpl.ControlUiPrimaryIdentity identity = primaryIdentity(accountId); + doAnswer( + invocation -> { + assertThat(invocation.getArgument(0, String.class)).isEqualTo(EMAIL); + assertThat(invocation.getArgument(1, String.class)).isEqualTo(SECRET); + assertWritableOwnerTransaction(); + events.add("primary-authentication"); + return identity; + }) + .when(primaryAuthentication) + .authenticateControlUiPrimaryIdentity(EMAIL, SECRET); + } + + private void primaryAuthenticationDenied() { + doAnswer( + invocation -> { + assertWritableOwnerTransaction(); + events.add("primary-authentication"); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + failedAttemptCommitted = true; + events.add("failed-login-attempt-committed"); + } + }); + throw new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, + "Rejected credential was " + SECRET); + }) + .when(primaryAuthentication) + .authenticateControlUiPrimaryIdentity(EMAIL, SECRET); + } + + private T inOwnerTransaction(Supplier action) { + return transaction.execute(status -> action.get()); + } + + private static void assertWritableOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + } + + private static void assertNoTransactionOrSynchronization() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + } + + 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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java index 509d581672..3e84bf697e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -41,7 +41,9 @@ import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.SimpleTransactionStatus; class AccountJwtJwksTrustedSourceTest { @@ -256,6 +258,25 @@ void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { verify(fixture.configMapClient, never()).observe(); } + @Test + void treatsDatabaseAndTransactionFailuresAsRetryableSourceUnavailability() { + List failures = + List.of( + new org.jooq.exception.DataAccessException("database unavailable"), + new DataAccessResourceFailureException("database unavailable"), + new TransactionException("transaction unavailable") {}); + + for (RuntimeException failure : failures) { + Fixture fixture = new Fixture(); + when(fixture.desiredStateRepository.readEnrollmentState(fixture.binding.accountBinding())) + .thenThrow(failure); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + } + @Test void doesNotTrustUnexpectedOwnerFailureByMatchingItsMessageText() { Fixture fixture = new Fixture(); 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 bf743a2a40..34194c27cf 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 @@ -76,6 +77,59 @@ public AccountControlUiOriginalOrderFixture( Clock.systemUTC()); } + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + boolean ownedCompositionConnections) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + Clock.systemUTC(), + null, + Clock.systemUTC(), + 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, @@ -142,112 +196,198 @@ public AccountControlUiOriginalOrderFixture( String migrationTarget, Clock serviceClock) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + serviceClock, + false); + } + + private AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + 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"); f = new AccountControlUiOwnerSourcesFixture( - jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); - signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); - var lifecycle = signerFixture; - lifecycle.commit(); - var originalSigner = f.tx(lifecycle.signer::captureCurrent); - assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) - .isEqualTo(originalSigner.receipt()); - custody("encryption", "enc1", 11); - custody("request-mac", "mac1", 29); - String PASSWORD = UUID.randomUUID().toString(); - var admin = RedisClient.create(RedisURI.Builder.redis(redisHost, redisPort).build()); - accountClient = - RedisClient.create( - RedisURI.Builder.redis(redisHost, redisPort) - .withAuthentication("account_coord_app", PASSWORD) - .build()); - accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); - try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { - connection - .sync() - .aclSetuser( - "account_coord_app", - new io.lettuce.core.AclSetuserArgs() - .reset() - .on() - .addPassword(PASSWORD) - .keyPattern("session:auth:token:*") - .addCommand(io.lettuce.core.protocol.CommandType.HELLO) - .addCommand(io.lettuce.core.protocol.CommandType.PING) - .addCommand( - io.lettuce.core.protocol.CommandType.CLIENT, - io.lettuce.core.protocol.CommandKeyword.SETINFO) - .addCommand( - io.lettuce.core.protocol.CommandType.ACL, - io.lettuce.core.protocol.CommandKeyword.WHOAMI) - .addCommand( - io.lettuce.core.protocol.CommandType.SCRIPT, - io.lettuce.core.protocol.CommandKeyword.LOAD) - .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) - .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.TIME)); - connection - .sync() - .dispatch( - TestAclCommand.INSTANCE, - new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), - new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) - .add("SETUSER") - .add("account_coord_app") - .add("+waitaof")); - awaitLocalAndReplicaAof(connection.sync()); - - } finally { - admin.shutdown(); + jdbcUrl, + username, + password, + temporary, + false, + gameDesignTenant, + migrationTarget, + ownedCompositionConnections, + creationEvidence); + RedisClient allocatedClient = null; + try { + signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); + var lifecycle = signerFixture; + lifecycle.commit(); + var originalSigner = f.tx(lifecycle.signer::captureCurrent); + assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) + .isEqualTo(originalSigner.receipt()); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + String PASSWORD = UUID.randomUUID().toString(); + var admin = RedisClient.create(RedisURI.Builder.redis(redisHost, redisPort).build()); + accountClient = + RedisClient.create( + RedisURI.Builder.redis(redisHost, redisPort) + .withAuthentication("account_coord_app", PASSWORD) + .build()); + allocatedClient = accountClient; + accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "account_coord_app", + new io.lettuce.core.AclSetuserArgs() + .reset() + .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( + io.lettuce.core.protocol.CommandType.CLIENT, + io.lettuce.core.protocol.CommandKeyword.SETINFO) + .addCommand( + io.lettuce.core.protocol.CommandType.ACL, + io.lettuce.core.protocol.CommandKeyword.WHOAMI) + .addCommand( + io.lettuce.core.protocol.CommandType.SCRIPT, + io.lettuce.core.protocol.CommandKeyword.LOAD) + .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) + .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() + .dispatch( + TestAclCommand.INSTANCE, + new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add("account_coord_app") + .add("+waitaof")); + awaitLocalAndReplicaAof(connection.sync()); + + } finally { + admin.shutdown(); + } + coordination = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AcknowledgementRequirements(1, 1, 5000), + testCatalog()); + operations = + migrationTarget != null + && AccountControlUiOwnerSourcesFixture.HISTORICAL_MIGRATION_TARGETS.contains( + migrationTarget) + ? new AccountHistoricalControlUiIssuanceRepository(f.dsl) + : new AccountControlUiIssuanceRepository(f.dsl); + publicSource = + org.mockito.Mockito.spy( + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager)); + actors = + new AccountControlUiActorService( + operations, + f.authority, + lifecycle.signer, + coordination, + publicSource, + f.fences, + f.manager, + actorClock); + issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), serviceClock), + coordination, + actors, + f.manager, + serviceClock, + 300_000L, + AccountControlUiOwnerSourcesFixture.CALLER); + } catch (Exception | Error failure) { + if (allocatedClient != null) { + try { + allocatedClient.shutdown(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + try { + f.closeOwnedConnections(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; } - coordination = - new AccountControlUiCoordination( - () -> accountClient.connect(ByteArrayCodec.INSTANCE), - new AcknowledgementRequirements(1, 1, 5000), - testCatalog()); - operations = - migrationTarget != null - && AccountControlUiOwnerSourcesFixture.HISTORICAL_MIGRATION_TARGETS.contains( - migrationTarget) - ? new AccountHistoricalControlUiIssuanceRepository(f.dsl) - : new AccountControlUiIssuanceRepository(f.dsl); - publicSource = - org.mockito.Mockito.spy( - new AccountJwtJwksTrustedSource( - lifecycle.client, - lifecycle.trust, - lifecycle.desired, - lifecycle.publication, - f.manager)); - actors = - new AccountControlUiActorService( - operations, - f.authority, - lifecycle.signer, - coordination, - publicSource, - f.fences, - f.manager, - actorClock); - issuance = - new AccountControlUiIssuanceService( - f.primary, - operations, - f.authority, - f.fences, - lifecycle.signer, - new AccountControlUiResponseCryptography( - new AccountControlUiKeyring(temporary.resolve("custody")), serviceClock), - coordination, - actors, - f.manager, - serviceClock, - 300_000L, - AccountControlUiOwnerSourcesFixture.CALLER); } /** The same persistence layout used by this fixture's genuine issuance and actor owners. */ @@ -259,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. @@ -388,7 +538,17 @@ public byte[] originalDraftOwnerReadback(DraftAuthorizationFenceBinding original @Override public void close() { - accountClient.shutdown(); + try { + accountClient.shutdown(); + } catch (RuntimeException | Error failure) { + try { + f.closeOwnedConnections(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + f.closeOwnedConnections(); } private static RedisScriptCatalog testCatalog() { 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 a8a0f9abff..db2d28a421 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 @@ -98,6 +98,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")); @@ -107,6 +108,7 @@ final class AccountControlUiOwnerSourcesFixture { final AccountControlUiAuthority authority; final AccountControlUiIssuanceService service; final DataSourceTransactionManager manager; + private final com.zaxxer.hikari.HikariDataSource compositionPool; private final DriverManagerDataSource migrationSource; private final String migrationSchema; final DraftAuthorizationFenceRepository fences; @@ -147,6 +149,48 @@ final class AccountControlUiOwnerSourcesFixture { UUID tenant, String migrationTarget) throws Exception { + this(jdbcUrl, username, password, root, installNegativeIssuer, tenant, migrationTarget, false); + } + + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant, + 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"); @@ -160,278 +204,297 @@ final class AccountControlUiOwnerSourcesFixture { var migrations = migrationConfiguration(); if (migrationTarget != null) migrations.target(migrationTarget); migrations.load().migrate(); - manager = new DataSourceTransactionManager(dataSource); - transactions = new TransactionTemplate(manager); - transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var generations = new AccountAuthorityGenerationRepository(dsl); - var outbox = new AccountAuthorityOutboxRepository(dsl); - var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - accounts = new AccountRepository(dsl, sourceEvidence); - restrictionBirths = new AccountPlatformRestrictionBirthRepository(dsl); - restrictionOperations = - new AccountPlatformRestrictionOperationRepository( - dsl, generations, outbox, sourceEvidence, restrictionBirths); - account = - tx( - () -> { - Account candidate = new Account(); - String suffix = UUID.randomUUID().toString(); - candidate.setUsername("owner-" + suffix); - candidate.setEmail(suffix + "@example.test"); - candidate.setPasswordHash(hash("test-only-disabled-password")); - candidate.setLoginAuthModes("EMAIL_OTP"); - return accounts.save(candidate); - }); - var creator = testCreation(account.getAccountUuid(), tenant); - var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); - tx( - () -> { - fresh.importVerified(creator.creationEvidence()); - generations.initializeTenantIfAbsent(tenant); - return null; - }); - var pairs = new AccountMembershipPairAuthorityRepository(dsl); - var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); - var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); - var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); - var reader = - new AccountCreatorMembershipSourceReader( - accounts, - new AccountJoinOperationRepository(dsl), - memberships, - pairs, - roles, - fresh, - generations, - outbox, - sourceEvidence, - bootstrapOperations); - var beans = new StaticListableBeanFactory(); - AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = - (actual, mutation) -> { - if (!creator.equals(actual) - || !TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Exact test-only external bootstrap fixture required"); - } - return mutation.get(); - }; - beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); - var bootstrap = - new AccountTenantCreationBootstrapService( - accounts, - fresh, - reader, - pairs, - memberships, - roles, - outbox, - new AccountAuditOutboxRepository(dsl), - bootstrapOperations, - beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); - tx(() -> bootstrap.bootstrap(creator)); - var party = - new IndividualCreatorPartySource( - UUID.randomUUID(), - account.getAccountUuid(), - VerificationStatus.VERIFIED, - 1L, - "test-only-policy", - 1L, - "test-only-verification", - 1L, - 1L); - insertTestParty(dsl, party); - var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); - tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); - fences = new DraftAuthorizationFenceRepository(dsl); - Map publications = new HashMap<>(); - Map actions = new HashMap<>(); - Map bindings = new HashMap<>(); - terms = - new AccountHostedTermsService( - manager, - new HostedTermsRepository(dsl), - parties, - fences, - id -> externalFixture(publications, id), - id -> externalFixture(actions, id), - new HostedTermsEnvironmentBindingRepository(dsl), - id -> externalFixture(bindings, id), - () -> { - requireOutsideTransaction(); - return boundary.get(); - }); - UUID publication = UUID.randomUUID(); - publications.put( - publication, - new AccountHostedTermsService.PublicationEvidence( - UUID.randomUUID(), - "Test-only Operator", - 1L, - bytes("Test-only initial terms"), - HostedTermsCatalogVersion.Materiality.INITIAL, - null, - null, - "test-only-publication-audit", - 1L, - "test-only-notice", - 1L, - Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); - var catalog = terms.publish(publication).candidate(); - UUID action = UUID.randomUUID(); - actions.put( - action, - new AccountHostedTermsService.AcceptanceAction( - action, - true, - account.getAccountUuid(), - party.creatorPartyId(), - catalog.hostedScopeId(), - catalog.versionId(), - catalog.documentDigest(), - catalog.operatorLegalIdentity(), - catalog.operatorIdentityVersion(), - "test-only-affirmative-action", - 1L, - OffsetDateTime.now(ZoneOffset.UTC))); - terms.accept(action); - UUID binding = UUID.randomUUID(); - bindings.put( - binding, - new HostedTermsEnvironmentBinding.PublicationEvidence( - "test-production", - catalog.hostedScopeId(), - catalog.operatorLegalIdentity(), - catalog.operatorIdentityVersion(), - catalog.versionId(), - catalog.sourceVersion(), - "test-only-environment-publisher", - "test-only-environment-publication/" + binding, - null, - null)); - terms.publishEnvironmentBinding(binding); - authority = - new AccountControlUiAuthority( - new AccountDraftSourceCompositionService( - dsl, parties, bootstrap, terms, sourceEvidence), - accounts, - sourceEvidence, - restrictionOperations, - dsl); - challenges = new AccountEmailLoginChallengeRepository(dsl); - tx( - () -> { - var challenge = new AccountEmailLoginChallenge(); - var now = LocalDateTime.now().withNano(0); - challenge.setAccountId(account.getId()); - challenge.setCodeHash(hash(OTP)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); - var primaryTarget = - new AccountServiceImpl( - accounts, - generations, - sourceEvidence, - outbox, - mock( - net.firedevops.firemud.accountservice.repository - .AccountPasswordResetOperationRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository - .class), - mock( - net.firedevops.firemud.accountservice.repository - .AccountSecurityStateOperationRepository.class), - mock( - net.firedevops.firemud.accountservice.service - .AccountPasswordResetDraftSourceChangeRepository.class), - mock(AccountAuditOutboxRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository - .class), - mock(AccountJoinOperationRepository.class), - challenges, - null, // Realm grants are not used by primary authentication. - null, // Tenant memberships are not used by primary authentication. - Mappers.getMapper(AccountMapper.class), - null, // Profiles are not used by primary authentication. - null, // Profile mapper is not used by primary authentication. - null, // Payment transactions are not used by primary authentication. - null, // Subscriptions are not used by primary authentication. - null, // External identities are not used by primary authentication. - null, // Password reset tokens are not used by primary authentication. - null, // Email verification tokens are not used by primary authentication. - null, // Notifications are not used by primary authentication. - 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, // JWT auth properties are not used by primary authentication. - null, // Game Session client is not used by primary authentication. - null, // Entity Management client is not used by primary authentication. - null, // JWT utility is not used by primary authentication. - null, // Session service is not used by primary authentication. - manager); - // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. - var primaryProxy = new ProxyFactory(primaryTarget); - primaryProxy.setProxyTargetClass(true); - primaryProxy.addAdvice( - new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); - primary = (AccountServiceImpl) primaryProxy.getProxy(); - if (!installNegativeIssuer) { - service = null; - return; + compositionPool = ownedCompositionConnections ? new com.zaxxer.hikari.HikariDataSource() : null; + try { + if (compositionPool != null) { + compositionPool.setPoolName("account-composition-" + schema); + compositionPool.setDataSource(dataSource); + compositionPool.setMaximumPoolSize(8); + compositionPool.setMinimumIdle(0); + } + javax.sql.DataSource ownerSource = compositionPool == null ? dataSource : compositionPool; + manager = new DataSourceTransactionManager(ownerSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(ownerSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + accounts = new AccountRepository(dsl, sourceEvidence); + restrictionBirths = new AccountPlatformRestrictionBirthRepository(dsl); + restrictionOperations = + new AccountPlatformRestrictionOperationRepository( + dsl, generations, outbox, sourceEvidence, restrictionBirths); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); + var creator = testCreation(account.getAccountUuid(), creationEvidence); + var fresh = + new FreshTenantIdentityAssociationRepository(dsl, creationEvidence.targetNamespace()); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sourceEvidence, + bootstrapOperations); + var beans = new StaticListableBeanFactory(); + AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = + (actual, mutation) -> { + if (!creator.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Exact test-only external bootstrap fixture required"); + } + return mutation.get(); + }; + beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + reader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + bootstrapOperations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account.getAccountUuid(), + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + fences = new DraftAuthorizationFenceRepository(dsl); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + fences, + id -> externalFixture(publications, id), + id -> externalFixture(actions, id), + new HostedTermsEnvironmentBindingRepository(dsl), + id -> externalFixture(bindings, id), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator", + 1L, + bytes("Test-only initial terms"), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account.getAccountUuid(), + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + authority = + new AccountControlUiAuthority( + new AccountDraftSourceCompositionService( + dsl, parties, bootstrap, terms, sourceEvidence), + accounts, + sourceEvidence, + restrictionOperations, + dsl); + challenges = new AccountEmailLoginChallengeRepository(dsl); + tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + var primaryTarget = + new AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountLogoutAllOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + mock(AccountJoinOperationRepository.class), + challenges, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. + Mappers.getMapper(AccountMapper.class), + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + null, // Subscriptions are not used by primary authentication. + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + 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, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. + manager); + // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. + var primaryProxy = new ProxyFactory(primaryTarget); + primaryProxy.setProxyTargetClass(true); + primaryProxy.addAdvice( + new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); + primary = (AccountServiceImpl) primaryProxy.getProxy(); + if (!installNegativeIssuer) { + service = null; + return; + } + var signerFixture = new AccountControlUiSignerFixture(this, root); + signerFixture.prepareInitialPrepublication(); + var signer = signerFixture.signer; + var operations = new AccountControlUiIssuanceRepository(dsl); + var crypto = + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); + var registry = + new AccountControlUiCoordination( + () -> { + coordinationCalls.incrementAndGet(); + throw new IllegalStateException("No physical Redis fixture in this negative proof"); + }, + new AcknowledgementRequirements(1, 1, 1000), + RedisScriptCatalog.fromContributions(List.of())); + var publicSource = + new AccountJwtJwksTrustedSource( + signerFixture.client, + signerFixture.trust, + signerFixture.desired, + signerFixture.publication, + manager); + var actors = + new AccountControlUiActorService( + operations, + authority, + signer, + registry, + publicSource, + fences, + manager, + Clock.systemUTC()); + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signer, + crypto, + registry, + actors, + manager, + Clock.systemUTC(), + 300_000L, + CALLER); + } catch (Exception | Error failure) { + try { + closeOwnedConnections(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; } - var signerFixture = new AccountControlUiSignerFixture(this, root); - signerFixture.prepareInitialPrepublication(); - var signer = signerFixture.signer; - var operations = new AccountControlUiIssuanceRepository(dsl); - var crypto = - new AccountControlUiResponseCryptography( - new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); - var registry = - new AccountControlUiCoordination( - () -> { - coordinationCalls.incrementAndGet(); - throw new IllegalStateException("No physical Redis fixture in this negative proof"); - }, - new AcknowledgementRequirements(1, 1, 1000), - RedisScriptCatalog.fromContributions(List.of())); - var publicSource = - new AccountJwtJwksTrustedSource( - signerFixture.client, - signerFixture.trust, - signerFixture.desired, - signerFixture.publication, - manager); - var actors = - new AccountControlUiActorService( - operations, - authority, - signer, - registry, - publicSource, - fences, - manager, - Clock.systemUTC()); - service = - new AccountControlUiIssuanceService( - primary, - operations, - authority, - fences, - signer, - crypto, - registry, - actors, - manager, - Clock.systemUTC(), - 300_000L, - CALLER); } AccountControlUiIssuanceService.Request request(String secret) { @@ -640,26 +703,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, @@ -742,6 +807,10 @@ private static String hash(String value) { } } + void closeOwnedConnections() { + if (compositionPool != null) compositionPool.close(); + } + /** Applies only the remaining real migrations, without rewriting retained fixture rows. */ void upgradeToCurrent() { migrationConfiguration().load().migrate(); 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..ad28fb69a8 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -0,0 +1,523 @@ +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 new file mode 100644 index 0000000000..a522ead2f2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -0,0 +1,602 @@ +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); + for (List bounded : + List.of( + membership.roles(), + membership.checkpoints(), + membership.sourceEvidence(), + membership.authorityTuple().privateRealmGrantVersions())) { + if (bounded.size() > 16) throw invalid("Bounded list required"); + } + 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"); + // Apply the decoder's exact JSON limits without recursively invoking parseCanonical. + try { + if (!JSON.readTree(bytes).isObject()) throw invalid("Player evidence object required"); + } catch (RuntimeException malformed) { + throw invalid("Player evidence exceeds decoder constraints"); + } + 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/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java new file mode 100644 index 0000000000..fdbe2d3000 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java @@ -0,0 +1,341 @@ +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +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; + +/** + * Closed canonical TENANT_OPERATION variant of Account's runtime entitlement evidence. + * + *

This value validates content, not source authenticity, transport authentication, freshness at + * use, capacity commitment, or player admission. Player-bound consumers must reject this variant. + * It has no account subject, issuer generation, membership, grant, or player-binding fields. + */ +public final class RuntimeTenantOperationEntitlementEvidence { + public static final String SCHEMA = "account-auth-evidence-bundle/v1"; + public static final String VARIANT = "TENANT_OPERATION"; + public static final int MAX_CANONICAL_BYTES = 64 * 1024; + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern DECIMAL = Pattern.compile("0|[1-9][0-9]{0,18}"); + private static final Set ROOT = + Set.of( + "schema", + "variant", + "bundleVersion", + "tenantId", + "requestId", + "callerWorkload", + "sourceKind", + "authorityAvailability", + "subscriptionStatus", + "provisioningStatus", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "entitlementVersion", + "tenantBillingSequence", + "tenantAuthorityGeneration", + "evaluatedAt", + "snapshotIdentity", + "evaluationIdentity", + "authorityTuple", + "outboxCheckpoints"); + private static final Set FLAGS = + Set.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts"); + private static final Set STATUSES = + Set.of("trialing", "active", "past_due", "grace", "suspended", "canceled"); + private static final JsonMapper JSON = + JsonMapper.builder( + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(8) + .maxStringLength(2048) + .maxNumberLength(19) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final byte[] canonicalBytes; + + private RuntimeTenantOperationEntitlementEvidence(byte[] canonicalBytes) { + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Production callers must derive every field inside the same locked Account source transaction. + */ + public static RuntimeTenantOperationEntitlementEvidence fromOwnerEvaluation( + Map fields) { + validate(fields); + return parseCanonical(canonicalize(fields)); + } + + public static RuntimeTenantOperationEntitlementEvidence parseCanonical(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) { + throw invalid("Bundle is absent or exceeds 64 KiB"); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("Bundle must be strict UTF-8"); + } + Map fields = parse(text); + validate(fields); + if (!Arrays.equals(bytes, canonicalize(fields))) { + throw invalid("Bundle bytes must be canonical"); + } + return new RuntimeTenantOperationEntitlementEvidence(bytes); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** A fresh decoded copy; changing it cannot change this immutable value. */ + public Map fields() { + return parse(new String(canonicalBytes, StandardCharsets.UTF_8)); + } + + /** Digest of exact canonical JSON, also used by Account's committed-source snapshot preimage. */ + public static String canonicalDigest(Map preimage) { + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalize(preimage))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static void validate(Map root) { + exact(root, ROOT, "bundle"); + equal(root.get("schema"), SCHEMA, "schema"); + equal(root.get("variant"), VARIANT, "variant"); + equal(root.get("authorityAvailability"), "AVAILABLE", "authorityAvailability"); + equal(root.get("bundleVersion"), "1", "bundleVersion"); + String tenant = uuid(root.get("tenantId"), "tenantId"); + uuid(root.get("requestId"), "requestId"); + String workload = text(root.get("callerWorkload"), "callerWorkload"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(workload) + .filter(identity -> identity.uri().equals(workload)) + .orElseThrow(() -> invalid("callerWorkload must be canonical")); + equal(peer.service(), "world-management-service", "callerWorkload service"); + String kind = text(root.get("sourceKind"), "sourceKind"); + if (!Set.of("PAID_HOSTING", "NON_PAID_DEMO").contains(kind)) { + throw invalid("Unsupported sourceKind"); + } + for (String flag : FLAGS) { + if (!(root.get(flag) instanceof Boolean)) throw invalid(flag + " must be explicit boolean"); + } + Object provisioning = root.get("provisioningStatus"); + Object status = root.get("subscriptionStatus"); + if (provisioning != null) { + if (!Set.of("pending", "provisioning").contains(provisioning) + || status != null + || !"PAID_HOSTING".equals(kind) + || FLAGS.stream().anyMatch(flag -> Boolean.TRUE.equals(root.get(flag)))) { + throw invalid("Provisioning evidence cannot grant hosting authority"); + } + } else if ("PAID_HOSTING".equals(kind)) { + if (!(status instanceof String value) || !STATUSES.contains(value)) { + throw invalid("Paid evidence requires resolved subscriptionStatus"); + } + } else if (status != null) { + throw invalid("Demo evidence cannot assert a paid subscriptionStatus"); + } + for (String field : ROOT) { + if (!Set.of("subscriptionStatus", "provisioningStatus").contains(field) + && root.get(field) == null) throw invalid(field + " cannot be null"); + } + Map quotas = object(root.get("quotas"), "quotas"); + exact( + quotas, + Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"), + "quotas"); + quotas.forEach((key, value) -> decimal(value, false, key)); + decimal(root.get("entitlementVersion"), true, "entitlementVersion"); + String billing = decimal(root.get("tenantBillingSequence"), true, "tenantBillingSequence"); + String generation = + decimal(root.get("tenantAuthorityGeneration"), true, "tenantAuthorityGeneration"); + String evaluated = text(root.get("evaluatedAt"), "evaluatedAt"); + try { + Instant instant = Instant.parse(evaluated); + if (!instant.toString().equals(evaluated) || !instant.isAfter(Instant.EPOCH)) { + throw invalid("evaluatedAt must be a canonical positive UTC instant"); + } + } catch (java.time.format.DateTimeParseException ex) { + throw invalid("evaluatedAt must be a canonical UTC instant"); + } + digest(root.get("snapshotIdentity"), "snapshotIdentity"); + digest(root.get("evaluationIdentity"), "evaluationIdentity"); + Map tuple = object(root.get("authorityTuple"), "authorityTuple"); + exact(tuple, Set.of("tenantAuthorityGeneration", "tenantBillingCutoff"), "authorityTuple"); + Map generations = + object(tuple.get("tenantAuthorityGeneration"), "tenant generations"); + exact(generations, Set.of(tenant), "tenant generations"); + equal(generations.get(tenant), generation, "tenant generation echo"); + Map cutoffs = object(tuple.get("tenantBillingCutoff"), "tenantBillingCutoff"); + exact(cutoffs, Set.of(tenant), "tenantBillingCutoff"); + Map cutoff = object(cutoffs.get(tenant), "tenant cutoff"); + exact( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"), + "tenant cutoff"); + equal(cutoff.get("tenantAuthorityGeneration"), generation, "cutoff generation"); + equal(cutoff.get("tenantBillingSequence"), billing, "cutoff billing sequence"); + String stream = TenantAuthorityEventV1Codec.streamKey(UUID.fromString(tenant)); + equal(cutoff.get("outboxStreamKey"), stream, "cutoff stream"); + String sequence = decimal(cutoff.get("outboxSequence"), true, "cutoff sequence"); + if (!(root.get("outboxCheckpoints") instanceof List checkpoints) + || checkpoints.size() != 1) { + throw invalid("Exactly one applicable tenant authority checkpoint is required"); + } + Map checkpoint = object(checkpoints.getFirst(), "checkpoint"); + exact( + checkpoint, + Set.of("outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest"), + "checkpoint"); + equal(checkpoint.get("outboxStreamKey"), stream, "checkpoint stream"); + equal(checkpoint.get("outboxSequence"), sequence, "checkpoint sequence"); + uuid(checkpoint.get("sourceEventId"), "checkpoint event ID"); + digest(checkpoint.get("sourceEventDigest"), "checkpoint event digest"); + } + + private static Map parse(String text) { + try { + return JSON.readValue(text, new TypeReference<>() {}); + } catch (RuntimeException ex) { + throw invalid("Bundle JSON is malformed"); + } + } + + private static byte[] canonicalize(Map fields) { + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + if (bytes.length > MAX_CANONICAL_BYTES) throw invalid("Canonical value exceeds 64 KiB"); + return bytes; + } catch (IOException ex) { + throw invalid("Cannot canonicalize bundle"); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map supplied)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + supplied.forEach( + (key, item) -> { + if (!(key instanceof String name)) throw invalid(field + " contains a non-text key"); + result.put(name, item); + }); + return result; + } + + private static void exact(Map value, Set expected, String field) { + if (value == null || !value.keySet().equals(expected)) + throw invalid(field + " has missing or extra fields"); + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > 2048) { + throw invalid(field + " must be bounded text"); + } + return text; + } + + private static String uuid(Object value, String field) { + String text = text(value, field); + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException ex) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return text; + } + + private static String decimal(Object value, boolean positive, String field) { + String text = text(value, field); + if (!DECIMAL.matcher(text).matches()) throw invalid(field + " must be canonical decimal text"); + try { + if (Long.parseLong(text) < (positive ? 1 : 0)) throw invalid(field + " is outside bounds"); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside BIGINT bounds"); + } + return text; + } + + private static void digest(Object value, String field) { + if (!(value instanceof String text) || !DIGEST.matcher(text).matches()) { + throw invalid(field + " must be a canonical SHA-256 digest"); + } + } + + private static void equal(Object supplied, Object expected, String field) { + if (!java.util.Objects.equals(supplied, expected)) throw invalid(field + " differs"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof RuntimeTenantOperationEntitlementEvidence value + && Arrays.equals(canonicalBytes, value.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + @Override + public String toString() { + return "RuntimeTenantOperationEntitlementEvidence[TENANT_OPERATION, redacted]"; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java new file mode 100644 index 0000000000..36ba5511fd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java @@ -0,0 +1,128 @@ +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 java.util.UUID; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed wire mapping only; canonical content and selectors do not authenticate their source. */ +public final class RuntimeTenantOperationEntitlementGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + RuntimeTenantOperationEntitlementEvidence.MAX_CANONICAL_BYTES + MAX_REQUEST_WIRE_BYTES + 32; + public static final long CALL_DEADLINE_SECONDS = 5L; + + private RuntimeTenantOperationEntitlementGrpcCodec() {} + + public enum SourceKind { + PAID_HOSTING, + NON_PAID_DEMO + } + + /** Comparison selectors, never an assertion of authenticated caller identity. */ + public record Request( + String targetNamespace, UUID tenantId, UUID requestId, SourceKind sourceKind) { + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + nonNil(tenantId); + nonNil(requestId); + Objects.requireNonNull(sourceKind, "Explicit entitlement source required"); + } + + public String expectedWorldWorkload() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/world-management-service"; + } + } + + public static ReadTenantOperationEntitlementRequest toRequest(Request request) { + Objects.requireNonNull(request); + return ReadTenantOperationEntitlementRequest.newBuilder() + .addSchemaVersion(1) + .addTargetNamespace(request.targetNamespace()) + .addTenantId(request.tenantId().toString()) + .addRequestId(request.requestId().toString()) + .addSourceKind(request.sourceKind().name()) + .build(); + } + + public static Request parseRequest(ReadTenantOperationEntitlementRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || one(wire.getSchemaVersionList()) != 1) { + throw new IllegalArgumentException("Exact bounded tenant-operation request required"); + } + return new Request( + one(wire.getTargetNamespaceList()), uuid(one(wire.getTenantIdList())), + uuid(one(wire.getRequestIdList())), SourceKind.valueOf(one(wire.getSourceKindList()))); + } + + public static ReadTenantOperationEntitlementResponse toResponse( + Request request, RuntimeTenantOperationEntitlementEvidence evidence) { + requireBinding(request, evidence); + var response = + ReadTenantOperationEntitlementResponse.newBuilder() + .addRequest(toRequest(request)) + .addCanonicalEvidence(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException("Tenant-operation response exceeds wire bound"); + } + return response; + } + + public static RuntimeTenantOperationEntitlementEvidence requireResponse( + Request expected, ReadTenantOperationEntitlementResponse wire) { + Objects.requireNonNull(expected); + if (wire == null + || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || !expected.equals(parseRequest(one(wire.getRequestList())))) { + throw new IllegalArgumentException("Exact bounded tenant-operation response required"); + } + var evidence = + RuntimeTenantOperationEntitlementEvidence.parseCanonical( + one(wire.getCanonicalEvidenceList()).toByteArray()); + requireBinding(expected, evidence); + return evidence; + } + + private static void requireBinding( + Request request, RuntimeTenantOperationEntitlementEvidence evidence) { + Objects.requireNonNull(request); + Map fields = Objects.requireNonNull(evidence).fields(); + if (!request.tenantId().toString().equals(fields.get("tenantId")) + || !request.requestId().toString().equals(fields.get("requestId")) + || !request.sourceKind().name().equals(fields.get("sourceKind")) + || !request.expectedWorldWorkload().equals(fields.get("callerWorkload"))) { + throw new IllegalArgumentException( + "Tenant-operation evidence differs from exact request/workload"); + } + } + + private static T one(List values) { + if (values.size() != 1) + throw new IllegalArgumentException("Exactly one transport member required"); + return values.getFirst(); + } + + private static UUID uuid(String text) { + UUID value = UUID.fromString(text); + nonNil(value); + if (!value.toString().equals(text)) + throw new IllegalArgumentException("Canonical UUID required"); + return value; + } + + private static void nonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } +} 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..88367c3487 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -0,0 +1,347 @@ +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 ownerEmissionUsesTheDecoderStringLimitBeforeReturningEvidence() { + var atLimit = target(); + atLimit.put("worldSlug", "a".repeat(65536)); + var value = capture(atLimit, facts(), sources(), NOW); + assertThat( + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes()) + .canonicalBytes()) + .containsExactly(value.canonicalBytes()); + var tooLong = target(); + tooLong.put("worldSlug", "a".repeat(65537)); + assertThatThrownBy(() -> capture(tooLong, facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Player evidence exceeds decoder constraints"); + } + + @Test + void ownerEmissionRejectsOversizedRoleInventoryBeforeReturningEvidence() { + var original = membership(); + var oversized = + new Snapshot( + original.issuerId(), + original.accountId(), + original.tenantId(), + original.membershipExists(), + original.membershipLifecycleState(), + original.gameplayAdmissionAllowed(), + original.membershipVersion(), + original.membershipAuthorityGeneration(), + java.util.stream.IntStream.range(0, 17).mapToObj(i -> "role" + i).toList(), + original.authorityTuple(), + original.issuanceFence(), + original.checkpoints(), + original.sourceEvidence()); + assertThatThrownBy( + () -> + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, + PEER, + "controlled-scope", + oversized, + target(), + facts(), + sources(), + NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Bounded list required"); + } + + @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-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java new file mode 100644 index 0000000000..fde12c4549 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java @@ -0,0 +1,233 @@ +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.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +/** Content proof only; controlled values are not authenticated Account source evidence. */ +class RuntimeTenantOperationEntitlementEvidenceTest { + private static final String TENANT = "44444444-4444-4444-8444-444444444444"; + private static final String STREAM = "account:auth-authority:v1:tenant/" + TENANT; + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void roundTripPreservesTenantOnlyShapeIndependentCountersAndImmutableValue() { + var value = RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields()); + assertThat(RuntimeTenantOperationEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + assertThat(value.fields()) + .containsEntry("tenantAuthorityGeneration", "5") + .containsEntry("entitlementVersion", "7") + .containsEntry("tenantBillingSequence", "11"); + assertThat(tuple(value.fields())) + .containsOnlyKeys("tenantAuthorityGeneration", "tenantBillingCutoff"); + value.fields().put("tenantId", UUID.randomUUID().toString()); + byte[] copy = value.canonicalBytes(); + copy[0] = 0; + assertThat(value.fields()).containsEntry("tenantId", TENANT); + } + + @Test + void playerIssuerAccountClaimsAndUnknownVariantsCannotEnterTenantOperation() { + for (String field : + List.of("callerAccountId", "verifiedConnectScopeId", "issuer", "membershipVersion")) { + var fields = fields(); + fields.put(field, "injected"); + reject(fields); + } + for (String field : + List.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff")) { + var fields = fields(); + var tuple = new LinkedHashMap<>(tuple(fields)); + tuple.put(field, "1"); + fields.put("authorityTuple", tuple); + reject(fields); + } + var fields = fields(); + fields.put("variant", "PLAYER_ADMISSION"); + reject(fields); + } + + @Test + void cutoffAndExactPositiveCheckpointCannotBeReplacedByFlatBillingSequence() { + var fields = fields(); + fields.put("tenantBillingSequence", "12"); + reject(fields); + fields = fields(); + fields.put("tenantAuthorityGeneration", "6"); + reject(fields); + fields = fields(); + fields.put("outboxCheckpoints", List.of(checkpoint("0"))); + reject(fields); + fields = fields(); + fields.put("outboxCheckpoints", List.of(checkpoint("3"), checkpoint("3"))); + reject(fields); + fields = fields(); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + TenantAuthorityEventV1Codec.tenantBillingStreamKey(UUID.fromString(TENANT)), + "outboxSequence", + "3", + "sourceEventId", + UUID.randomUUID().toString(), + "sourceEventDigest", + DIGEST))); + reject(fields); + } + + @Test + void statusesHaveExplicitPresenceAndProvisioningCannotGrantAdmission() { + var fields = fields(); + fields.remove("subscriptionStatus"); + reject(fields); + fields = fields(); + fields.put("subscriptionStatus", null); + fields.put("provisioningStatus", "pending"); + reject(fields); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) { + fields.put(flag, false); + } + assertThat(RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields).fields()) + .containsEntry("provisioningStatus", "pending") + .containsEntry("subscriptionStatus", null); + fields.put("provisioningStatus", null); + fields.put("sourceKind", "NON_PAID_DEMO"); + assertThat(RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields).fields()) + .containsEntry("subscriptionStatus", null); + } + + @Test + void malformedUtf8DuplicatesUnknownSchemaOverflowAndNoncanonicalBytesFailClosed() { + byte[] canonical = + RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields()).canonicalBytes(); + String text = new String(canonical, StandardCharsets.UTF_8); + rejectBytes((" " + text).getBytes(StandardCharsets.UTF_8)); + rejectBytes( + text.replaceFirst("\\{", "{\"schema\":\"account-auth-evidence-bundle/v1\",") + .getBytes(StandardCharsets.UTF_8)); + rejectBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + rejectBytes(new byte[RuntimeTenantOperationEntitlementEvidence.MAX_CANONICAL_BYTES + 1]); + for (String decimal : List.of("01", "-1", "9223372036854775808")) { + var fields = fields(); + fields.put("entitlementVersion", decimal); + reject(fields); + } + var fields = fields(); + fields.put("schema", "account-auth-evidence-bundle/v2"); + reject(fields); + fields = fields(); + fields.put("tenantId", "44444444444444448444444444444444"); + reject(fields); + } + + @Test + void absentNullOrUnavailableAuthorityCannotProduceUsableEvidence() { + var absent = fields(); + absent.remove("authorityAvailability"); + reject(absent); + var missing = fields(); + missing.put("authorityAvailability", null); + reject(missing); + var unavailable = fields(); + unavailable.put("authorityAvailability", "UNAVAILABLE"); + reject(unavailable); + } + + private static Map fields() { + Map fields = new LinkedHashMap<>(); + fields.put("schema", RuntimeTenantOperationEntitlementEvidence.SCHEMA); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("tenantId", TENANT); + fields.put("requestId", "11111111-1111-4111-8111-111111111111"); + fields.put("callerWorkload", "spiffe://firemud/ns/prod/sa/world-management-service"); + fields.put("sourceKind", "PAID_HOSTING"); + fields.put("subscriptionStatus", "active"); + fields.put("provisioningStatus", null); + fields.put("gameplayAvailable", true); + fields.put("allowPublicJoin", true); + fields.put("allowNewGameplayBindings", true); + fields.put("allowNewInstanceStarts", true); + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", "2026-11-02T12:00:00Z"); + fields.put("snapshotIdentity", DIGEST); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(TENANT, "5"), + "tenantBillingCutoff", + Map.of( + TENANT, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + STREAM, + "outboxSequence", + "3")))); + fields.put("outboxCheckpoints", List.of(checkpoint("3"))); + return fields; + } + + private static Map checkpoint(String sequence) { + return Map.of( + "outboxStreamKey", + STREAM, + "outboxSequence", + sequence, + "sourceEventId", + "22222222-2222-4222-8222-222222222222", + "sourceEventDigest", + DIGEST); + } + + @SuppressWarnings("unchecked") + private static Map tuple(Map fields) { + return (Map) fields.get("authorityTuple"); + } + + private static void reject(Map fields) { + assertThatThrownBy(() -> RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void rejectBytes(byte[] bytes) { + assertThatThrownBy(() -> RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java new file mode 100644 index 0000000000..05a52e836e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.common.account.authority; + +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.evidence; +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.request; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec.SourceKind; +import org.junit.jupiter.api.Test; + +class RuntimeTenantOperationEntitlementGrpcCodecTest { + @Test + void bothExplicitSourcesPreserveExactCanonicalEvidence() { + for (var source : SourceKind.values()) { + var request = request(source); + var evidence = evidence(request); + assertThat( + RuntimeTenantOperationEntitlementGrpcCodec.parseRequest( + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request))) + .isEqualTo(request); + assertThat( + RuntimeTenantOperationEntitlementGrpcCodec.requireResponse( + request, + RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence))) + .isEqualTo(evidence); + } + } + + @Test + void rejectsMissingDuplicateUnknownUnboundedAndNoncanonicalRequestMembers() throws Exception { + var wire = + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request(SourceKind.PAID_HOSTING)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + new ReadTenantOperationEntitlementRequest[] { + wire.toBuilder().clearSourceKind().build(), + wire.toBuilder().addSourceKind("PAID_HOSTING").build(), + wire.toBuilder().addTenantId(wire.getTenantId(0)).build(), + wire.toBuilder().addRequestId(wire.getRequestId(0)).build(), + wire.toBuilder().addSchemaVersion(1).build(), + wire.toBuilder().addTargetNamespace("firemud").build(), + wire.toBuilder().setSourceKind(0, "DEFAULT").build(), + wire.toBuilder().setTenantId(0, "00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId(0, "11111111111141118111111111111111").build(), + wire.toBuilder().setTargetNamespace(0, "a".repeat(2048)).build(), + wire.toBuilder().setUnknownFields(unknown).build() + }) { + assertThatThrownBy(() -> RuntimeTenantOperationEntitlementGrpcCodec.parseRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + // Actual repeated protobuf field occurrences survive parsing for cardinality rejection. + byte[] bytes = wire.toByteArray(); + byte[] duplicate = new byte[bytes.length * 2]; + System.arraycopy(bytes, 0, duplicate, 0, bytes.length); + System.arraycopy(bytes, 0, duplicate, bytes.length, bytes.length); + assertThatThrownBy( + () -> + RuntimeTenantOperationEntitlementGrpcCodec.parseRequest( + ReadTenantOperationEntitlementRequest.parseFrom(duplicate))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsResponseCardinalityUnknownFieldsBindingsAndBadCanonicalValue() { + var request = request(SourceKind.PAID_HOSTING); + var evidence = evidence(request); + var wire = RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + java.util.List.of( + wire.toBuilder().clearRequest().build(), + wire.toBuilder().addRequest(wire.getRequest(0)).build(), + wire.toBuilder().addCanonicalEvidence(wire.getCanonicalEvidence(0)).build(), + wire.toBuilder().clearCanonicalEvidence().build(), + wire.toBuilder().setCanonicalEvidence(0, ByteString.copyFromUtf8("{}")).build(), + wire.toBuilder().setCanonicalEvidence(0, ByteString.copyFrom(new byte[65537])).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setRequest(0, wire.getRequest(0).toBuilder().setSourceKind(0, "NON_PAID_DEMO")) + .build())) { + assertThatThrownBy( + () -> RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (var changed : + java.util.List.of( + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "other", request.tenantId(), request.requestId(), request.sourceKind()), + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", UUID.randomUUID(), request.requestId(), request.sourceKind()), + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", request.tenantId(), UUID.randomUUID(), request.sourceKind()), + request(SourceKind.NON_PAID_DEMO))) { + var substituted = + wire.toBuilder() + .setRequest(0, RuntimeTenantOperationEntitlementGrpcCodec.toRequest(changed)) + .build(); + assertThatThrownBy( + () -> + RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(changed, substituted)) + .isInstanceOf(IllegalArgumentException.class); + } + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java new file mode 100644 index 0000000000..f2aad8b046 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.account.authority; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** Controlled transport fixture only, never genuine Account source or currentness proof. */ +public final class TenantOperationEntitlementTransportFixture { + private TenantOperationEntitlementTransportFixture() {} + + public static RuntimeTenantOperationEntitlementGrpcCodec.Request request( + RuntimeTenantOperationEntitlementGrpcCodec.SourceKind source) { + return new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + source); + } + + public static RuntimeTenantOperationEntitlementEvidence evidence( + RuntimeTenantOperationEntitlementGrpcCodec.Request request) { + String tenant = request.tenantId().toString(); + String stream = TenantAuthorityEventV1Codec.streamKey(request.tenantId()); + String digest = "sha256:" + "a".repeat(64); + Map fields = new LinkedHashMap<>(); + fields.put("schema", RuntimeTenantOperationEntitlementEvidence.SCHEMA); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("tenantId", tenant); + fields.put("requestId", request.requestId().toString()); + fields.put("callerWorkload", request.expectedWorldWorkload()); + fields.put("sourceKind", request.sourceKind().name()); + fields.put( + "subscriptionStatus", + request.sourceKind() == RuntimeTenantOperationEntitlementGrpcCodec.SourceKind.PAID_HOSTING + ? "active" + : null); + fields.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) { + fields.put(flag, true); + } + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", "2026-11-02T12:00:00Z"); + fields.put("snapshotIdentity", digest); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(tenant, "5"), + "tenantBillingCutoff", + Map.of( + tenant, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + stream, + "outboxSequence", + "3")))); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + stream, + "outboxSequence", + "3", + "sourceEventId", + "22222222-2222-4222-8222-222222222222", + "sourceEventDigest", + digest))); + return RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields); + } +} 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/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/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/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..05742f597d --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java @@ -0,0 +1,79 @@ +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(); + try { + AccountBootstrapRosterReadContract.requireRequest(request); + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT); + return; + } + 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 + | AccountBootstrapRosterReadService.TargetChangedException precondition) { + refuse(observer, Status.FAILED_PRECONDITION); + 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..245d1c3885 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java @@ -0,0 +1,96 @@ +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 IllegalStateException( + "Account bootstrap roster read requires no ambient transaction or synchronization"); + } + } + + 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..7cc00fe148 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,70 @@ 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(); + if (rows.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); + } + var actors = + new ArrayList< + net.firedevops.firemud.entitymanagement.bootstrap + .AccountBootstrapRosterActorProjection>(rows.size()); + for (var row : rows) { + Integer level = row.get(CHARACTERS.LEVEL); + if (level == null) { + throw new IllegalStateException("CANONICAL_ROSTER_LEVEL_NULL"); + } + actors.add( + new net.firedevops.firemud.entitymanagement.bootstrap + .AccountBootstrapRosterActorProjection( + row.get(CHARACTERS.CHARACTER_UUID), row.get(CHARACTERS.NAME), level)); + } + return actors; + } + 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 +1292,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..7a170ef426 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -0,0 +1,381 @@ +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 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 io.grpc.stub.StreamObserver; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.UUID; +import javax.net.ssl.SSLSession; +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.AccountBootstrapRosterPeerInterceptor; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadContract; +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.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.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.springframework.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 + @SuppressWarnings("unchecked") + 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); + var receiver = + new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + withControlledAccountPeer(() -> receiver.readAccountBootstrapRoster(f.request(), observer)); + assertReceiverFailure(observer, Status.Code.FAILED_PRECONDITION); + 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())) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage( + "Account bootstrap roster read requires no ambient transaction or synchronization") + .hasNoCause(); + }); + verifyNoInteractions(client, repository); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @SuppressWarnings("unchecked") + void ambientTransactionOrSynchronizationIsInternalBeforeAnySourceOrSql(boolean transactionActive) + throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + var receiver = + new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + TransactionSynchronizationManager.setActualTransactionActive(transactionActive); + if (!transactionActive) TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> service.read(f.request())) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage( + "Account bootstrap roster read requires no ambient transaction or synchronization") + .hasNoCause(); + + withControlledAccountPeer(() -> receiver.readAccountBootstrapRoster(f.request(), observer)); + + assertReceiverFailure(observer, Status.Code.INTERNAL); + verifyNoInteractions(client, repository); + } finally { + if (!transactionActive) TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + + @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); + } + } + + @Test + @SuppressWarnings("unchecked") + void receiverKeepsMalformedRequestsInvalidWithoutCallingService() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var service = mock(AccountBootstrapRosterReadService.class); + var receiver = + new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + + withControlledAccountPeer( + () -> + receiver.readAccountBootstrapRoster( + f.request().toBuilder().setCanonicalAccountUuid("malformed").build(), observer)); + + assertReceiverFailure(observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(service); + } + + @Test + @SuppressWarnings("unchecked") + void receiverClassifiesStoredProjectionAndResponseValidationFailuresAsInternal() + throws Exception { + for (String invalidProjection : List.of("duplicate", "negative-level", "null-level")) { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(f.evidence()); + if ("null-level".equals(invalidProjection)) { + when(repository.readAccountBootstrapRoster(any(), any())) + .thenThrow(new IllegalStateException("CANONICAL_ROSTER_LEVEL_NULL")); + } else if ("negative-level".equals(invalidProjection)) { + when(repository.readAccountBootstrapRoster(any(), any())) + .thenAnswer( + ignored -> + List.of( + new AccountBootstrapRosterActorProjection( + UUID.randomUUID(), "Persisted Actor", -1))); + } else { + var actor = + new AccountBootstrapRosterActorProjection(UUID.randomUUID(), "Persisted Actor", 0); + // The valid persisted rows form an invalid response because actor identity repeats. + when(repository.readAccountBootstrapRoster(any(), any())).thenReturn(List.of(actor, actor)); + } + var receiver = + new AccountBootstrapRosterReadGrpcService( + service(client, repository), AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + + withControlledAccountPeer(() -> receiver.readAccountBootstrapRoster(f.request(), observer)); + + assertReceiverFailure(observer, Status.Code.INTERNAL); + verify(repository).readAccountBootstrapRoster(any(), eq(f.target())); + } + } + + private static void assertReceiverFailure( + StreamObserver observer, Status.Code expected) { + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()).isEqualTo(expected); + assertThat(failure.getValue()) + .hasMessage(expected.name() + ": Account bootstrap roster read refused") + .hasNoCause(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + + /** Controlled peer context for status mapping only; this is not physical mTLS proof. */ + @SuppressWarnings("unchecked") + private static void withControlledAccountPeer(Runnable action) throws Exception { + ServerCall call = + mock(ServerCall.class); + MethodDescriptor + descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()) + .thenReturn(AccountBootstrapRosterPeerInterceptor.METHOD_NAME); + when(call.getMethodDescriptor()).thenReturn(descriptor); + X509Certificate leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn( + List.of( + List.of( + 6, + "spiffe://firemud/ns/" + + AccountBootstrapRosterFixture.NAMESPACE + + "/sa/account-service"))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + ServerCallHandler next = + mock(ServerCallHandler.class); + when(next.startCall(any(), any())) + .thenAnswer( + ignored -> { + action.run(); + return new ServerCall.Listener() {}; + }); + + new AccountBootstrapRosterPeerInterceptor(AccountBootstrapRosterFixture.NAMESPACE) + .interceptCall(call, new Metadata(), next); + + verify(next).startCall(any(), any()); + } + + 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/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java new file mode 100644 index 0000000000..7cf31c7442 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java @@ -0,0 +1,127 @@ +package unit.net.firedevops.firemud.entitymanagement.repository; + +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled SQL-result mapping only; this does not execute a writer or PostgreSQL/mTLS. */ +class CharacterRepositoryBootstrapRosterTest { + @Test + void nullableStoredLevelRefusesTheEntireProjectionWithBoundedPrecondition() throws Exception { + var source = AccountBootstrapRosterFixture.create(); + var fixture = + new SqlRows( + source, + new ActorRow(UUID.fromString("11111111-1111-4111-8111-111111111111"), "Valid", 7), + new ActorRow(UUID.fromString("22222222-2222-4222-8222-222222222222"), "Missing", null)); + + assertThatThrownBy(fixture::read) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LEVEL_NULL"); + assertThat(fixture.queries).hasSize(2); + } + + @Test + void actualZeroAndNonzeroLevelsPreserveTheirSameRowUuidAndName() throws Exception { + var source = AccountBootstrapRosterFixture.create(); + UUID zeroActor = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID nonzeroActor = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var fixture = + new SqlRows( + source, + new ActorRow(zeroActor, "Zero Level", 0), + new ActorRow(nonzeroActor, "Nonzero Level", 7)); + + assertThat(fixture.read()) + .containsExactly( + new AccountBootstrapRosterActorProjection(zeroActor, "Zero Level", 0), + new AccountBootstrapRosterActorProjection(nonzeroActor, "Nonzero Level", 7)); + assertThat(fixture.queries).hasSize(2); + } + + @Test + void missingOwnerTransactionRefusesBeforeSql() throws Exception { + var fixture = new SqlRows(AccountBootstrapRosterFixture.create()); + + assertThatThrownBy( + () -> fixture.repository.readAccountBootstrapRoster(fixture.account, fixture.target)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Account bootstrap discovery requires owner transaction"); + assertThat(fixture.queries).isEmpty(); + } + + private record ActorRow(UUID characterUuid, String displayName, Integer level) {} + + private static final class SqlRows { + final UUID account; + final CanonicalGameplayRosterTarget target; + final CharacterRepository repository; + final List queries = new ArrayList<>(); + + SqlRows(AccountBootstrapRosterFixture.Fixture source, ActorRow... actors) { + account = UUID.fromString(source.request().getCanonicalAccountUuid()); + target = source.target(); + var resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + String sql = context.sql().toLowerCase(Locale.ROOT); + queries.add(sql); + assertThat(sql).startsWith("select "); + if (sql.contains("entity_playable_state_namespace_scopes")) { + assertThat(context.bindings()) + .containsExactly(target.tenantUuid(), target.playableStateNamespaceId()); + var field = ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE; + var rows = resultDsl.newResult(field); + rows.add(resultDsl.newRecord(field).values(target.playableStateScope().name())); + return new MockResult[] {new MockResult(rows.size(), rows)}; + } + assertThat(sql).contains("characters"); + assertThat(context.bindings()) + .contains( + account, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.playableStateScope().name(), + "OWNER_RESOLVED"); + var rows = + resultDsl.newResult(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME, CHARACTERS.LEVEL); + for (var actor : actors) { + rows.add( + resultDsl + .newRecord(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME, CHARACTERS.LEVEL) + .values(actor.characterUuid(), actor.displayName(), actor.level())); + } + return new MockResult[] {new MockResult(rows.size(), rows)}; + }; + repository = + new CharacterRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + } + + List read() { + boolean active = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + return repository.readAccountBootstrapRoster(account, target); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(active); + } + } + } +} 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..febbbd1d8d --- /dev/null +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -0,0 +1,272 @@ +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; +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() {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The retained generated protobuf request message is immutable.") + public record Fixture( + AccountBootstrapRosterReadRequest request, + CanonicalGameplayRosterTarget target, + 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(); + 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/build.gradle.kts b/services/game-session-service/build.gradle.kts index ab2b77fa28..c2bd44fa92 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -187,10 +187,14 @@ 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 new file mode 100644 index 0000000000..dd5f9c3147 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java @@ -0,0 +1,396 @@ +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()); + // Account owns evaluatedAt ordering; an independent receiver clock cannot make it a + // not-before bound. Preserve the exact expiry without any skew allowance or extension. + if (!clock.instant().isBefore(evidence.validUntil())) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + 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)); + } + + 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/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/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index d450e1041f..5a9188b515 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -131,10 +131,10 @@ public void listVisiblePublicProductionAdmissionTargets( } final ListVisiblePublicProductionAdmissionTargetsResponse response; try { - var before = readPreseededDiscoveryTargets(); + var before = readDiscoveryTargets(); // Validate the complete first read before treating it as an expected collection. CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(parsed, before); - var after = readPreseededDiscoveryTargets(); + var after = readDiscoveryTargets(); response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(parsed, after); if (!new HashSet<>(before).equals(new HashSet<>(after))) { fail(observer, Status.FAILED_PRECONDITION); @@ -196,13 +196,13 @@ public void resolvePublishedRealmAdmissionTarget( sendSource(observer, response); } - private List readPreseededDiscoveryTargets() { + private List readDiscoveryTargets() { var selected = new ArrayList(); var tenants = new HashSet(); var tenantSlugs = new HashSet(); var realms = new HashSet(); for (var route : routeReader.readVisiblePublicProductionTargets()) { - // Qualify every source before filtering, so an excluded policy cannot hide bad authority. + // Qualify the complete collection before returning either supported discovery policy. var target = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetEvidence( CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetEvidence(toTarget(route))); @@ -215,11 +215,11 @@ private List readPreseededDiscoveryTargets() { || !realms.add(target.realmId())) { throw new IllegalArgumentException("Discovery source has invalid or duplicate authority"); } - if ("PRESEEDED_ONLY".equals(target.characterCreationPolicy())) { - selected.add(target); - } else if (!"PLAYER_CREATED".equals(target.characterCreationPolicy())) { + if (!"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + && !"PLAYER_CREATED".equals(target.characterCreationPolicy())) { throw new IllegalArgumentException("Discovery source has unsupported character policy"); } + selected.add(target); } return List.copyOf(selected); } 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..38387b4fc1 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,81 @@ 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(assignmentLockAttempted.await(10, TimeUnit.SECONDS)) + .as("Assignment claim must reach its lock attempt before the retained claim can finish") + .isTrue(); + 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(); } } 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/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..0c778a8049 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java @@ -0,0 +1,410 @@ +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 new file mode 100644 index 0000000000..74d686b52e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -0,0 +1,932 @@ +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.ManagedChannel; +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 exactAccountPeerReceivesUncompressedCurrentLoginCredentialAndReturnsBoundCanonicalEvidence() + 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(); + assertThat(client.buildStub(mock(ManagedChannel.class)).getCallOptions().getCompressor()) + .isNull(); + 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 firstPartyPlayerCreatedTargetRefusesBeforeRpcOrCredentialDisclosure() throws Exception { + var context = context(); + doReturn("PLAYER_CREATED").when(context.resolvedTarget()).characterCreationPolicy(); + 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, () -> true)) + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact live LOGIN custody and verified player-admission scope required"); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + assertThat(observedPeer).hasValue(null); + } finally { + stop(server); + } + } + + @Test + void independentReceiverClockMayPrecedeAccountEvaluationWithoutExtendingExpiry() + 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()); + Clock receiverClock = Clock.fixed(NOW.minusMillis(25), ZoneOffset.UTC); + try (var client = client(server, receiverClock)) { + client.init(); + var result = client.read(context, READ_REQUEST, login, () -> true); + assertThat(result.evaluatedAt()).isEqualTo(NOW).isAfter(receiverClock.instant()); + assertThat(result.validUntil()) + .isEqualTo(Instant.ofEpochMilli(context.claims().expiresAtMillis())); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(longs = {-1, 0, 1}) + void exactPaidReceiptExpiryHasNoReceiverSkewAllowance(long offsetMillis) throws Exception { + var context = context(); + var login = loginCustody(); + Instant receiptExpiry = NOW.plusSeconds(1); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + context.resolvedTarget(), + Instant.ofEpochMilli(context.claims().expiresAtMillis()), + login.evidence(), + (target, sources) -> sources.put("paidReceiptValidUntil", receiptExpiry.toString()), + () -> {}); + try (var client = + client(server, Clock.fixed(receiptExpiry.plusMillis(offsetMillis), ZoneOffset.UTC))) { + client.init(); + if (offsetMillis < 0) { + assertThat(client.read(context, READ_REQUEST, login, () -> true).validUntil()) + .isEqualTo(receiptExpiry); + } else { + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + assertThat(calls).hasValue(1); + } 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(); + var refusal = + assertThatThrownBy( + () -> client.read(scope, original, transport, selectedReadId, login, current)) + .as(change); + switch (change) { + case "stale-custody", "throwing-custody", "null-custody", "custody-lost-before-rpc" -> + refusal + .isExactlyInstanceOf(StatusRuntimeException.class) + .hasMessage("CANCELLED: Account player-admission entitlement read did not complete") + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.CANCELLED)); + case "original-request", + "original-context", + "attempt-fence", + "transport-session", + "transport-proxy", + "expired-login", + "expired-scope" -> + refusal + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact authenticated lobby evidence required"); + case "closed-login" -> + refusal + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Controlled closed LOGIN"); + case "wrong-namespace", + "private-scope", + "created-policy", + "durable-abort", + "read-correlation" -> + refusal + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage( + "Exact live LOGIN custody and verified player-admission scope required"); + default -> throw new IllegalArgumentException(change); + } + 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(); + var successfulResponses = new AtomicInteger(); + 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); + } + successfulResponses.incrementAndGet(); + }; + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + expiry, + login.evidence(), + (value, sources) -> {}, + afterRead); + try (var client = client(server, movingClock)) { + client.init(); + var refusal = + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, current::get)); + switch (change) { + case "custody" -> + refusal + .isExactlyInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.CANCELLED)); + case "scope-expiry", "login-expiry" -> + refusal + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact authenticated lobby evidence required"); + case "closed-login" -> + refusal.isExactlyInstanceOf(IllegalStateException.class).hasMessage("Closed LOGIN"); + default -> throw new IllegalArgumentException(change); + } + assertThat(calls).hasValue(1); + assertThat(successfulResponses).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + assertThat(observedPeer).hasValue(GS_PEER); + } 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); + // Live-input changes happen only after the successful response is fully encoded. + var response = + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( + presented.request(), evidence); + afterRead.run(); + observer.onNext(response); + 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); + if (sources.get("paidReceiptValidUntil") != null) { + facts.put("sourceKind", "PAID_HOSTING"); + facts.put("subscriptionStatus", "active"); + } + + 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/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index 391e6129fe..f09b40e6dd 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 @@ -100,7 +100,7 @@ void discoveryReturnsOnlyCompleteUnchangedOwnerCollectionRegardlessOfIterationOr } @Test - void discoveryExcludesValidPlayerCreatedTargetsOnBothReads() { + void discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads() { var preseeded = discoveryTarget("first", "First world"); var created = discoveryTarget("second", "Created world", "PLAYER_CREATED"); for (var initial : List.of(List.of(preseeded, created), List.of(created))) { @@ -121,9 +121,15 @@ void discoveryExcludesValidPlayerCreatedTargetsOnBothReads() { CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest( discoveryRequest()), captured.getValue()); - assertThat(result.targets()).hasSize(initial.size() - 1); + assertThat(result.targets()).hasSize(initial.size()); assertThat(result.targets()) - .allMatch(target -> target.characterCreationPolicy().equals("PRESEEDED_ONLY")); + .extracting( + target -> target.canonicalTenantId(), target -> target.characterCreationPolicy()) + .containsExactlyInAnyOrderElementsOf( + initial.stream() + .map( + target -> tuple(target.canonicalTenantId(), target.characterCreationPolicy())) + .toList()); verify(routes, times(2)).readVisiblePublicProductionTargets(); } } @@ -357,7 +363,7 @@ private static CanonicalPlayableTarget discoveryTarget(String slug, String displ } private static CanonicalPlayableTarget discoveryTarget( - String slug, String displayName, String policy) { + 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"); @@ -417,7 +423,7 @@ private static CanonicalPlayableTarget discoveryTarget( CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, false, Instant.parse("2026-10-25T00:00:00Z"), - policy); + creationPolicy); } @Test diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java new file mode 100644 index 0000000000..2a32457a99 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.worldmanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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; + +/** Explicit, unregistered World consumer of Account's protected tenant-operation source read. */ +public final class AccountTenantOperationEntitlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceBlockingStub> { + private final String namespace; + + public AccountTenantOperationEntitlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties, "Tenant-operation entitlement reads"), + channelFactory, + AccountTenantOperationEntitlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + this.namespace = namespace; + } + + public void init() throws IOException { + initOnce( + "Tenant-operation entitlement client is closed", "Tenant-operation client has no stub"); + } + + /** Samples actual Account evidence; the owner of a later action must enforce its currentness. */ + public ProtectedRead read(RuntimeTenantOperationEntitlementGrpcCodec.Request request) { + requireNoAmbientSql("Account entitlement reads require no ambient World transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Entitlement request must target the configured namespace"); + } + var response = + requireInitializedStub("Tenant-operation entitlement client is unavailable") + .withDeadlineAfter( + RuntimeTenantOperationEntitlementGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readTenantOperationEntitlement( + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request)); + if (response == null) { + throw new IllegalStateException("Account returned no tenant-operation evidence"); + } + try { + return new ProtectedRead( + request, RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(request, response)); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid tenant-operation evidence", invalid); + } + } + + /** + * Only a successful protected read can construct this provenance wrapper. Never admission + * authority. + */ + public static final class ProtectedRead { + private final RuntimeTenantOperationEntitlementGrpcCodec.Request request; + private final RuntimeTenantOperationEntitlementEvidence evidence; + + private ProtectedRead( + RuntimeTenantOperationEntitlementGrpcCodec.Request request, + RuntimeTenantOperationEntitlementEvidence evidence) { + this.request = request; + this.evidence = evidence; + } + + public RuntimeTenantOperationEntitlementGrpcCodec.Request request() { + return request; + } + + public RuntimeTenantOperationEntitlementEvidence evidence() { + return evidence; + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountTenantOperationEntitlementReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withMaxInboundMessageSize( + RuntimeTenantOperationEntitlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize( + RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java new file mode 100644 index 0000000000..86690ef819 --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java @@ -0,0 +1,342 @@ +package net.firedevops.firemud.worldmanagement.client; + +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.evidence; +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.request; +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.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +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.nio.file.Path; +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.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantOperationEntitlementGrpcService; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec.SourceKind; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Real loopback mTLS with a controlled source owner; no physical source/currentness qualification. + */ +class AccountTenantOperationEntitlementClientMtlsTest { + @Test + void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFallback( + @TempDir Path temporary) throws Exception { + var pki = pki(temporary); + var owner = mock(AccountTenantOperationEntitlementOwner.class); + var paid = request(SourceKind.PAID_HOSTING); + var demo = request(SourceKind.NON_PAID_DEMO); + when(owner.evaluatePaid(any())) + .thenAnswer( + invocation -> { + var actual = + (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); + assertThat(actual) + .isEqualTo( + new AccountTenantOperationEntitlementOwner.Request( + paid.tenantId(), paid.requestId(), paid.expectedWorldWorkload())); + return evidence(paid); + }); + when(owner.evaluateDemo(any())) + .thenAnswer( + invocation -> { + var actual = + (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); + assertThat(actual) + .isEqualTo( + new AccountTenantOperationEntitlementOwner.Request( + demo.tenantId(), demo.requestId(), demo.expectedWorldWorkload())); + return evidence(demo); + }); + var receiver = new AccountTenantOperationEntitlementGrpcService(owner, "firemud"); + Server server = + receiver + .createUnregisteredServer( + "localhost:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()) + .start(); + try { + try (var client = client(pki, temporary, "world", server.getPort())) { + assertThatThrownBy(() -> client.read(paid)).isInstanceOf(IllegalStateException.class); + client.init(); + var read = client.read(paid); + assertThat(read.request()).isEqualTo(paid); + assertThat(read.evidence()).isEqualTo(evidence(paid)); + assertThat(client.read(demo).evidence()).isEqualTo(evidence(demo)); + verify(owner, org.mockito.Mockito.times(1)).evaluatePaid(any()); + doThrow( + new AccountTenantOperationEntitlementOwner.SourceUnavailableException( + "private source detail")) + .when(owner) + .evaluatePaid(any()); + assertStatus(() -> client.read(paid), Status.Code.UNAVAILABLE); + for (RuntimeException failure : + new RuntimeException[] { + new IllegalArgumentException("private namespace mismatch"), + new NullPointerException("private codec failure") + }) { + doThrow(failure).when(owner).evaluatePaid(any()); + assertThatThrownBy(() -> client.read(paid)) + .satisfies( + thrown -> { + assertThat(Status.fromThrowable(thrown).getCode()) + .isEqualTo(Status.Code.INTERNAL); + var details = io.grpc.protobuf.StatusProto.fromThrowable(thrown); + assertThat(details).isNotNull(); + assertThat(details.getDetailsCount()).isEqualTo(1); + var detail = + details + .getDetails(0) + .unpack(net.firedevops.firemud.shared.v1.ErrorDetail.class); + assertThat(detail.getCode()).isEqualTo("INTERNAL"); + assertThat(detail.getMessage()).doesNotContain("private"); + }); + } + verify(owner, org.mockito.Mockito.times(1)).evaluateDemo(any()); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(demo)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + for (String wrong : new String[] {"wrong-client", "other-world"}) { + try (var client = client(pki, temporary, wrong, server.getPort())) { + client.init(); + assertStatus(() -> client.read(paid), Status.Code.PERMISSION_DENIED); + } + } + } finally { + stop(server); + } + // Calling a handler directly, even with a syntactically valid request, supplies no TLS + // assertion. + var observer = new OutcomeObserver(); + receiver.readTenantOperationEntitlement( + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(paid), observer); + assertThat(observer.failureCode).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + @Test + void clientRefusesWrongOwnerBeforeSendingAndRejectsChangedOrMalformedEvidence( + @TempDir Path temporary) throws Exception { + var pki = pki(temporary); + var request = request(SourceKind.PAID_HOSTING); + var response = + new AtomicReference<>( + RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence(request))); + var calls = new AtomicInteger(); + for (String alias : new String[] {"wrong-server", "other-account", "account"}) { + var identity = pki.identity(alias); + Server server = + NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + new AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceImplBase() { + @Override + public void readTenantOperationEntitlement( + ReadTenantOperationEntitlementRequest ignored, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onNext(response.get()); + observer.onCompleted(); + } + }) + .build() + .start(); + try (var client = client(pki, temporary, "world", server.getPort())) { + client.init(); + if (!"account".equals(alias)) { + assertStatus(() -> client.read(request), Status.Code.UNAUTHENTICATED); + assertThat(calls).hasValue(0); + } else { + assertThat(client.read(request).evidence()).isEqualTo(evidence(request)); + var changed = + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", request.tenantId(), UUID.randomUUID(), request.sourceKind()); + response.set( + response.get().toBuilder() + .setCanonicalEvidence( + 0, + com.google.protobuf.ByteString.copyFrom(evidence(changed).canonicalBytes())) + .build()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + response.set( + response.get().toBuilder() + .addCanonicalEvidence(response.get().getCanonicalEvidence(0)) + .build()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } + } finally { + stop(server); + } + } + } + + @Test + void clientRejectsPlaintextBeforeChannelCreation() { + var properties = new net.firedevops.firemud.common.grpc.CommonGrpcClientProperties(); + properties.setPlaintext(true); + var channels = mock(GrpcChannelFactory.class); + assertThatThrownBy( + () -> + new AccountTenantOperationEntitlementClient( + new ServiceEndpointsProperties(), properties, channels, "firemud")) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verifyNoInteractions(channels); + } + + @Test + void receiverRejectsMalformedUnknownDuplicateWrongNamespaceAndOversizedRequestsBeforeSource( + @TempDir Path temporary) throws Exception { + var pki = pki(temporary); + var owner = mock(AccountTenantOperationEntitlementOwner.class); + var receiver = new AccountTenantOperationEntitlementGrpcService(owner, "firemud"); + Server server = + receiver + .createUnregisteredServer( + "localhost:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()) + .start(); + var channel = + new GrpcChannelFactory() + .buildChannel( + "localhost:" + server.getPort(), + 6565, + pki.clientProperties(temporary, pki.identity("world")), + false); + try { + var stub = + AccountTenantOperationEntitlementReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request(SourceKind.PAID_HOSTING)); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + java.util.List.of( + wire.toBuilder().clearSourceKind().build(), + wire.toBuilder().setSourceKind(0, "UNKNOWN_SOURCE").build(), + wire.toBuilder().addRequestId(wire.getRequestId(0)).build(), + wire.toBuilder().setUnknownFields(unknown).build())) { + assertStatus( + () -> stub.readTenantOperationEntitlement(invalid), Status.Code.INVALID_ARGUMENT); + } + assertStatus( + () -> + stub.readTenantOperationEntitlement( + wire.toBuilder().setTargetNamespace(0, "other").build()), + Status.Code.PERMISSION_DENIED); + var oversized = + wire.toBuilder() + .setSourceKind( + 0, + "a".repeat(RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES + 1)) + .build(); + assertThat(oversized.getSerializedSize()) + .isGreaterThan(RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + assertStatus( + () -> stub.readTenantOperationEntitlement(oversized), Status.Code.RESOURCE_EXHAUSTED); + org.mockito.Mockito.verifyNoInteractions(owner); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + stop(server); + } + } + + private static LoopbackMtlsTestPki.Pki pki(Path temporary) throws Exception { + return LoopbackMtlsTestPki.create( + temporary, + "Tenant operation transport test CA", + identity("account", "firemud", "account-service", true), + identity("wrong-server", "firemud", "game-session-service", true), + identity("other-account", "other", "account-service", true), + identity("world", "firemud", "world-management-service", false), + identity("wrong-client", "firemud", "game-session-service", false), + identity("other-world", "other", "world-management-service", false)); + } + + private static IdentitySpec identity( + String alias, String namespace, String service, boolean server) { + return new IdentitySpec(alias, "spiffe://firemud/ns/" + namespace + "/sa/" + service, server); + } + + private static AccountTenantOperationEntitlementClient client( + LoopbackMtlsTestPki.Pki pki, Path temporary, String alias, int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + return new AccountTenantOperationEntitlementClient( + endpoints, + pki.clientProperties(temporary, pki.identity(alias)), + new GrpcChannelFactory(), + "firemud"); + } + + private static void assertStatus( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, Status.Code code) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void stop(Server server) throws Exception { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static final class OutcomeObserver + implements StreamObserver { + private Status.Code failureCode; + + @Override + public void onNext(ReadTenantOperationEntitlementResponse response) { + throw new AssertionError("Unauthenticated direct handler must not return evidence"); + } + + @Override + public void onError(Throwable failure) { + failureCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + throw new AssertionError("Unexpected completion"); + } + } +}