From ceeb5046b27893a6714a4c292ac94025a8311a66 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:37:59 +1300 Subject: [PATCH 01/22] Implement atomic Account password-reset authority source receipts --- ...uthority-and-gameplay-session-ownership.md | 4 +- ...30-risk-based-active-session-revocation.md | 12 +- .../account-service/api-contracts.md | 10 + .../system-architecture-authentication.md | 17 +- ...em-architecture-jwt-and-token-contracts.md | 6 +- design/project-management/ai-observations.md | 4 + .../player-access-and-session.md | 2 + services/account-service/build.gradle.kts | 2 + ...countPasswordResetOperationRepository.java | 316 ++++++++++ .../repository/AccountRepository.java | 44 ++ .../PasswordResetTokenRepository.java | 3 +- .../service/impl/AccountServiceImpl.java | 556 ++++++++++++++++- ...ount_password_reset_operation_receipts.sql | 91 +++ .../AccountApplicationIntegrationTest.java | 314 ++++++++-- ...horityProducerPostgresIntegrationTest.java | 535 ++++++++++++++++ ...tPasswordResetOperationRepositoryTest.java | 132 ++++ .../service/impl/AccountServiceImplTest.java | 589 ++++++++++++++++-- .../PasswordResetAuthorityEventV1Codec.java | 372 +++++++++++ ...-auth-password-reset-event-v1-vectors.json | 136 ++++ ...asswordResetAuthorityEventV1CodecTest.java | 167 +++++ 20 files changed, 3178 insertions(+), 134 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V41__account_password_reset_operation_receipts.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java diff --git a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md index 25897359ed..a786d277b2 100644 --- a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md +++ b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md @@ -52,13 +52,13 @@ Later clarification: [ADR 0132](./adr-0132-namespace-scoped-single-character-con Game Session consumes authoritative Account membership, entitlement, and revocation state. It stores only the token identity and freshness metadata needed to validate a binding, such as token hash, issued-at time, and `membershipVersion`; it must not make a persisted raw backend JWT the durable session authority. -For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its schema is `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained evidence or an exact Account checkpoint lookup proves the complete required authority evidence: the same `authorityTuple`, positive `issuanceFence`, complete `outboxCheckpoints` set, event ID, sequence, recomputed event digest, exact stream key, and `issuerAuthGeneration`. A sequence/event/digest/stream/generation match without the complete tuple, fence, and checkpoint set is not duplicate proof. Missing, partial, generation-only, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same complete evidence comparison before the watermark or generation advances; a lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. This local projection is a revocation-consumer cache, not an authority source, and Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. +For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its schema is `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. The issuer source event and the recipient evidence it affects remain separate under [Authentication's source-event contract](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence): source events bind issuer scope and committed source progress, while Account readback binds the consumed event/checkpoint to the recipient's complete `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one snapshot. The source event is not required to carry that recipient tuple or fence. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained source evidence or an exact Account checkpoint lookup proves the same event identity/digest, source sequence, exact stream key, and issuer source progress, and the Account recipient readback proves the complete same-snapshot `authorityTuple`, positive `issuanceFence`, and complete `outboxCheckpoints` set. A source-event match without that recipient binding is not duplicate proof. Missing, partial, generation-only, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same source-event and recipient-binding comparison before the watermark or generation advances; a lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. This local projection is a revocation-consumer cache, not an authority source, and Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. ### Canonical Checkpoint And Source-Evidence Binding [ADR 0030](./adr-0030-risk-based-active-session-revocation.md) owns the unchanged `outboxCheckpoints` entry schema: exactly `{outboxStreamKey, outboxSequence}`, with one entry for every applicable authority stream. `compareOutboxCheckpointEntries(a, b)` compares the unsigned UTF-8 bytes of `outboxStreamKey` lexicographically and places the shorter key first when one is a prefix. Duplicate stream keys, locale collation, Unicode normalization, case folding, alternate escaping, or another ordering are invalid. -Event identity and digest remain separate same-snapshot source evidence rather than members of `outboxCheckpoints`. For each checkpoint, retained applied-source evidence or an exact Account lookup binds `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, outboxCheckpoints}` from one Account linearization point. Delivery, refresh, rebind, binding CAS, acknowledgement, retries, and duplicate detection carry or resolve that complete binding without adding fields to the checkpoint carrier. A latest entry, aggregate maximum, projection-only value, partial source-evidence match, or evidence assembled from separate snapshots is invalid and quarantines the affected scope. +Event identity, digest, and stream position remain source evidence separate from the `outboxCheckpoints` carrier. For each checkpoint, an Account-authenticated same-snapshot readback binds the consumed source event evidence to the recipient's complete `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one Account linearization point. Scope-wide issuer/account/tenant source events are not required to carry that recipient tuple or fence; the closed membership event retains the exact fields declared by its v1 schema. Delivery, refresh, rebind, binding CAS, acknowledgement, retries, and duplicate detection carry or resolve the complete recipient binding and exact source evidence without adding fields to the checkpoint carrier. A latest entry, aggregate maximum, projection-only value, partial source-evidence match, or evidence assembled from separate snapshots is invalid and quarantines the affected scope. ### Operation Partition diff --git a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md index dd666691d9..9574e50d04 100644 --- a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md +++ b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md @@ -28,7 +28,7 @@ The previous target distinguished soft and hard billing states and required even ### Canonical Authority Tuple Boundary -[JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to revocation events, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite authority fence copied alongside the tuple, never a substitute for a tuple member. Account carries the same fence through applicable canonical outbox and logout/revocation evidence so consumers cannot accept authority evidence assembled across different Account linearization points. +[JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to Account-authenticated recipient authority evidence, revocation-local admission decisions, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite recipient fence copied alongside the tuple, never a substitute for a tuple member. [Authentication](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence) owns the distinction between scope-wide source events and recipient evidence: Account readback binds consumed source evidence to the recipient tuple and fence from one snapshot. The closed membership event v1 schema retains its declared tuple and fence fields. Revocation-local admission decisions, exact-binding leases, and gameplay bindings also carry the complete canonical `outboxCheckpoints` set: one exact `{outboxStreamKey, outboxSequence}` entry for every applicable scoped outbox stream. This set is admission freshness evidence, not a member of `authorityTuple` or a general JWT/registry claim, and any stream coordinates embedded in cutoff evidence must equal their corresponding set entries. @@ -64,12 +64,12 @@ For every admission or replacement operation, `membershipBaseline` is one immuta ### Delivery And Bounded Enforcement -- Account is the sole authority writer. One Account database transaction, or one composite Account CAS/fence that atomically covers every applicable member of `authorityTuple`, commits the authority change, applicable account-security or tenant-billing cutoff evidence, applicable private-realm grant version, the applicable `issuanceFence`, and the outbox row. Independent row updates are not an acceptable substitute. Redis and other downstream projections are derived outputs. A cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. [ADR 0036](./adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) supersedes timestamp watermark ordering for bulk token-revocation decisions. +- Account is the sole authority writer. One Account database transaction, or an equivalent Account-owned source-scope CAS, commits the source mutation, exact scope generation/source-version advance, applicable account-security or tenant-billing cutoff evidence, applicable private-realm grant version, any Account-local issuance-fence advance required by that mutation, and the scoped outbox row. Issuer-wide and tenant-wide source changes do not invent a recipient fence or require per-account fanout. Recipient readback and lease finalization still compare every applicable source scope and the actual Account issuance fence together at one Account linearization point under [Authentication](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence). Independent row updates are not an acceptable substitute. Redis and other downstream projections are derived outputs. A cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. [ADR 0036](./adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) supersedes timestamp watermark ordering for bulk token-revocation decisions. - The durable revocation outbox stream key is exactly `account:auth-authority:v1:`. The exact `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound private/playtest grant scope produced by the [canonical grant authority-stream scope codec](../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Account allocates `outboxSequence` contiguously starting at `1` independently for each exact stream key, in the same transaction/CAS as the authority mutation. `tenantBillingSequence` remains the separate Account billing sequence for the exact tenant and is copied into `tenantBillingCutoff` when applicable. -- `tenantBillingSequence` has one canonical billing-cutoff stream mapping: for tenant ``, every billing cutoff advances the Account-owned sequence and is emitted on `account:auth-authority:v1:tenant/`. The `tenantBillingCutoff[tenantId]` evidence carries that exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; no second billing stream or tenant-local sequence source exists. Billing consumption maintains two independent ledgers: a source-delivery ledger keyed by each exact `outboxStreamKey`, with its own `lastAppliedOutboxSequence` and bounded retained duplicate evidence `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies, and a separate `lastAppliedTenantBillingSequence` for each tenant. The source ledger advances for every event on that stream, including non-billing events; the tenant billing ledger advances only for billing-cutoff events. `tenantBillingSequence` is never used as the source watermark or duplicate identity, and an outbox watermark is never used as billing-sequence evidence. Each delivered event must be contiguous at `lastAppliedOutboxSequence + 1` for its exact stream; a billing-cutoff event must additionally satisfy the exact tenant/stream mapping and `tenantBillingSequence == lastAppliedTenantBillingSequence + 1`, while a non-billing event must not advance or regress the billing sequence. Matching duplicates are no-ops only when the complete retained same-snapshot evidence matches the canonical schema or an exact Account lookup proves that evidence; a same-key gap, conflicting duplicate, missing evidence, billing-sequence regression, or mismatch stops the affected scope, reconciles from Account, and advances either independent ledger only after the corresponding Account checkpoint proves coverage. A first event never initializes either ledger from delivered data: it first installs the exact Account snapshot, source watermark/evidence, and separate billing watermark under the bootstrap rule below, and only the next source sequence (`installed watermark + 1`) can be accepted. +- `tenantBillingSequence` has one canonical billing-cutoff stream mapping: for tenant ``, every billing cutoff advances the Account-owned sequence and is emitted on `account:auth-authority:v1:tenant/`. The `tenantBillingCutoff[tenantId]` evidence carries that exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; no second billing stream or tenant-local sequence source exists. Billing consumption maintains two independent ledgers: a source-delivery ledger keyed by each exact `outboxStreamKey`, with its own `lastAppliedOutboxSequence` and bounded retained source-event evidence under the event's closed schema, plus a separate `lastAppliedTenantBillingSequence` for each tenant. Where recipient authority comparison applies, Account-authenticated same-snapshot evidence binds the consumed source checkpoint to the complete applicable `authorityTuple`, actual `issuanceFence`, `membershipBaseline` when applicable, and complete `outboxCheckpoints` set. The source ledger advances for every event on that stream, including non-billing events; the tenant billing ledger advances only for billing-cutoff events. `tenantBillingSequence` is never used as the source watermark or duplicate identity, and an outbox watermark is never used as billing-sequence evidence. Each delivered event must be contiguous at `lastAppliedOutboxSequence + 1` for its exact stream; a billing-cutoff event must additionally satisfy the exact tenant/stream mapping and `tenantBillingSequence == lastAppliedTenantBillingSequence + 1`, while a non-billing event must not advance or regress the billing sequence. Matching source duplicates are no-ops only when retained source-event evidence matches its closed schema and, where recipient authority applies, the same-snapshot Account binding also matches; an exact Account lookup may resolve either evidence component. A same-key gap, conflicting duplicate, missing evidence, billing-sequence regression, or mismatch stops the affected scope, reconciles from Account, and advances either independent ledger only after the corresponding Account checkpoint proves coverage. A first event never initializes either ledger from delivered data: it first installs the exact Account snapshot, source watermark/evidence, and separate billing watermark under the bootstrap rule below, and only the next source sequence (`installed watermark + 1`) can be accepted. - Every authority change that can affect a new gameplay binding advances its applicable tuple member and the scoped outbox sequence in the same Account transaction/CAS. The Account-owned admission decision exposes the exact tuple and the complete `outboxCheckpoints` set it covers. Game Session may create a binding only after every checkpoint entry has its exact stream watermark at or beyond `outboxSequence` and every corresponding authority/index projection confirms coverage of that entry. A missing, stale, gapped, ambiguous, or otherwise unconfirmed checkpoint or projection fails closed before binding creation. -- An issuer-generation cutoff is also an active-session revocation authority, not only a token-validation rule. Account advances the issuer generation and emits the committed outbox event with the issuer scope, new generation, `issuanceFence`, and cutoff checkpoint. Game Session owns only the derived consumer-local projection `session:game:auth:issuer-generation:v1:` and applies that event with set-if-greater semantics; it never writes or mutates Account's canonical `session:auth:generation:*` projection. Duplicate or older events are no-ops only when the exact source evidence rule below is satisfied; a generation-only match is insufficient. A gap or unavailable, stale, regressed, or ambiguous projection triggers authoritative reconciliation and fail-closed admission. Every active gameplay binding persists the issuer generation captured at admission, and the issuer cutoff is applied to all affected bindings across tenants. -- Every new gameplay binding and every reconnect/resume admission must also use an Account-owned exact-binding admission lease. The lease contains the target `{accountId, tenantId}` binding identity, exact `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, complete `outboxCheckpoints` set, a monotonic `leaseFence`, and a short expiry; grace resume uses the existing `resumeActivationLease` as this contract's exact-resume specialization. Game Session's binding CAS must include the expected old binding generation, exact lease identity, `leaseFence`, `issuanceFence`, and the same tuple, unchanged baseline, and checkpoint set and may publish only a non-admissible provisional record until Account durably finalizes the same lease as `COMMITTED`. Account authority advancement, membership-baseline changes, and lease finalization serialize through the same composite Account CAS across every applicable tuple and baseline member: if any issuer, account, tenant, membership, grant, billing, security, lifecycle, membership-version, or membership-generation value advances before finalization, the fence changes, finalization fails, and any provisional local binding is removed or remains blocked. A stale, missing, expired, ambiguous, or unfenced lease never becomes an admissible binding. This lease/fence predicate is the conditional authority checked by the Game Session binding CAS; it is an ordered idempotent protocol across stores, not a claimed cross-store transaction. +- An issuer-generation cutoff is also an active-session revocation authority, not only a token-validation rule. Account advances the issuer generation and emits its scoped source event under the [Authentication source-event contract](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence); that issuer-wide source event does not carry a recipient `issuanceFence` or complete recipient tuple. Account-authenticated readback binds the consumed source event and checkpoint to the recipient's complete `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one snapshot. Game Session owns only the derived consumer-local projection `session:game:auth:issuer-generation:v1:` and applies the event with set-if-greater semantics; it never writes or mutates Account's canonical `session:auth:generation:*` projection. Duplicate or older events are no-ops only when exact source evidence and the Account recipient binding below are satisfied; a generation-only match is insufficient. A gap or unavailable, stale, regressed, or ambiguous projection triggers authoritative reconciliation and fail-closed admission. Every active gameplay binding persists the issuer generation captured at admission, and the issuer cutoff is applied to all affected bindings across tenants. +- Every new gameplay binding and every reconnect/resume admission must also use an Account-owned exact-binding admission lease. The lease contains the target `{accountId, tenantId}` binding identity, exact `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, complete `outboxCheckpoints` set, a monotonic `leaseFence`, and a short expiry; grace resume uses the existing `resumeActivationLease` as this contract's exact-resume specialization. Game Session's binding CAS must include the expected old binding generation, exact lease identity, `leaseFence`, `issuanceFence`, and the same tuple, unchanged baseline, and checkpoint set and may publish only a non-admissible provisional record until Account durably finalizes the same lease as `COMMITTED`. Account authority advancement, membership-baseline changes, and lease finalization serialize through the same composite Account CAS across every applicable tuple and baseline member: if any issuer, account, tenant, membership, grant, billing, security, lifecycle, membership-version, or membership-generation value advances before finalization, the composite comparison no longer matches, finalization fails, and any provisional local binding is removed or remains blocked. An issuer or tenant source advance can invalidate that comparison without changing the Account-local issuance-fence scalar. A stale, missing, expired, ambiguous, or unfenced lease never becomes an admissible binding. This lease/fence predicate is the conditional authority checked by the Game Session binding CAS; it is an ordered idempotent protocol across stores, not a claimed cross-store transaction. - Game Session remains the owner of gameplay binding records, the binding CAS, all bounded active-binding indexes, and socket/admission termination. Account finalization commits only the Account-owned lease, decision, authority snapshot, complete `outboxCheckpoints` set, and idempotency evidence; it does not create, delete, or mutate a Game Session binding or index. If Account reconciliation finds a committed or abandoned lease with no matching admissible Game Session binding, Account emits durable orphan evidence and a fenced cleanup request keyed to the exact request, lease, binding, and fence. Gateway performs any matching edge-token deny/clear cleanup, and Game Session validates the cleanup fence before removing or quarantining the binding and its indexes. Account may reconcile the decision evidence and record cleanup acknowledgements, but local Account cleanup is not physical gameplay cleanup or proof of completion. - Game Session consumes revocation events durably and idempotently. Each event type has its own closed wire schema. [Authentication](../system-architecture-authentication.md#membership-event-digest) owns the exact `account-auth-authority-event/v1` membership-event fields and digest preimage; this ADR's revocation evidence requirements do not add `outboxCheckpoints`, `occurredAt`, or any other field to that event. Other revocation event types require a declared schema before emission. For the membership event, `sourceScope` must decode to the scope encoded by `outboxStreamKey`, and `membershipVersion` is the complete exact one-tenant map defined above. `eventDigest` is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over the UTF-8 bytes of the RFC 8785 JSON Canonicalization Scheme serialization of the exact declared event object, excluding only `eventDigest`. Account computes it from the authoritative snapshot before publishing; the consumer recomputes and compares it before applying or acknowledging the event. Undeclared, duplicate, missing, alternate-numeric, or alternate-serialization event fields are invalid. - The complete `outboxCheckpoints` set is a separate Account-authenticated carrier from the same authority snapshot, not an event field or an implicit extension of its digest preimage. [ADR 0022](./adr-0022-account-authority-and-gameplay-session-ownership.md#canonical-checkpoint-and-source-evidence-binding) owns its checkpoint and source-evidence binding. The carrier binds the exact event ID and digest, source stream key and sequence, applicable `authorityTuple`, `issuanceFence`, unchanged `membershipBaseline` when membership applies, and the complete canonical stream-key-ordered checkpoint set. Each checkpoint has exactly `{outboxStreamKey, outboxSequence}`; the event's stream entry equals its committed sequence, and positive checkpoints have their separate same-snapshot event ID/digest source evidence. A missing, extra, stale, regressed, cross-scope, differently ordered, separately sourced, or mismatched carrier fails closed. The event alone, or its valid digest without the matching authenticated carrier, is insufficient for admission, duplicate acceptance, or projection advancement. @@ -123,7 +123,7 @@ Checking Account or Redis before every command gives a tighter revocation observ ## Implementation and Proof Obligations -- Implement monotonic `authorityTuple` issuer/account/tenant/membership fields, `privateRealmGrantVersions`, applicable `accountSecurityCutoff` and `tenantBillingCutoff`, and `issuanceFence` with transactional durable advances, durable outbox and logout/revocation evidence carrying the exact fence, and idempotent consumers. +- Implement monotonic `authorityTuple` issuer/account/tenant/membership fields, `privateRealmGrantVersions`, applicable `accountSecurityCutoff` and `tenantBillingCutoff`, and `issuanceFence` with transactional durable advances and scope-specific source events. Preserve the distinction in [Authentication](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence): Account-authenticated recipient evidence carries the exact fence and binds each consumed source checkpoint to the applicable tuple and complete checkpoint set; the closed membership event keeps its declared v1 schema. Prove idempotent consumers against both evidence layers. - Define, validate, observe, and prove the event-delivery, gap-detection, scheduler-jitter, retry, datastore-timeout, clock-skew, and `B_termination` sub-budgets using the single canonical equation above; include partial-outage and deadline-exhaustion behavior without adding `B_termination_setup` or the capacity term a second time. - Expose the applicable Account-owned authority tuple and complete committed `outboxCheckpoints` set through the admission decision, track every corresponding projection's application of its checkpoint, and fail closed before creating any new gameplay binding while any checkpoint is stale, gapped, ambiguous, or unconfirmed. - Implement the Account-owned exact-binding admission lease and monotonic `leaseFence` for new binding and reconnect/resume admission, bind the applicable complete `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, and complete `outboxCheckpoints` set into that lease, include the lease/fence, unchanged baseline, and checkpoint set in the atomic Game Session binding CAS, and keep the local record provisional until Account `COMMITTED` finalization. Prove cutoff-before-finalization rejects admission, finalization-before-cutoff admits only the then-current authority and is later revoked through the bounded event path, and any stale, ambiguous, expired, or uncertain lease state fails closed without leaving an admissible binding. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b0cc8506a5..165a9cdb4a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -137,6 +137,16 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `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. +### Account-Owned Password-Reset Authority Commit + +Password reset is an account-wide security cutoff, not only a password-row update. Account must commit the password change, one-use reset-token consumption, account generation/source-version advance, applicable Account-local issuance-fence advance, immutable reset receipt, and [password-reset source event](../../system-architecture-authentication.md#account-password-reset-source-event) together. Missing or contradictory Account UUID provenance, source generation/history, or commit/readback evidence denies before mutation; reset never guesses or enrolls a missing authority baseline. Downstream revocation and recipient consumption are separate proof obligations, not an atomic transaction with Redis or Game Session. + +The Account-issued, unpredictable one-use reset token identifies one logical reset attempt. Account uses its SHA-256 token hash as the stable internal request identity; raw token bytes never appear in the source event or retained receipt. The receipt binds the exact verified Account UUID, token hash, original token deadline, and SHA-256 of the salted Argon2 password verifier committed to the Account row. It retains neither an additional password verifier nor a fast plaintext-password digest. A versioned private request digest binds those immutable values in the fixed order `[operationKind, accountId, tokenHash, tokenExpiresAt, passwordVerifierDigest]`, using UTF-8 byte-length framing with domain `account-password-reset-request/v1` and `operationKind=PASSWORD_RESET`. Exact retry first proves that the current Account password verifier matches its recorded digest, then verifies the submitted password against that slow verifier and compares immutable request/event/receipt evidence before returning the same lifecycle-only completion; it does not hash a replacement password, consume another token, advance authority again, or issue a credential. A changed Account password postcondition fails closed as superseded rather than being mislabeled a changed caller request. With the original postcondition proved, reusing the same token identity with a different password is a conflict, not another reset. The original token deadline still limits this retry; this operation does not inherit bare-LOGIN's separately authorized expired-context recovery. + +The private digest frame starts with its domain and then each field in the declared order. Each component is its UTF-8 byte sequence preceded by a four-byte big-endian byte count. `accountId` is the canonical non-nil UUID string; both hash fields are exactly 64 lowercase hexadecimal characters. `tokenExpiresAt` is the persisted timezone-less deadline's exact `LocalDateTime.toString()` representation, without inventing an offset or converting retained deadlines to UTC. The immutable internal IDs are `account-password-reset-request-v1:` and `account-password-reset-event-v1:`. + +The stored receipt and event must be read back exactly before success, including after a lost response. Concurrent retries serialize on the exact Account/source scope and one-use token claim; token consumption, password mutation, authority advance, event append and receipt insertion roll back together on any failure. Receipt cleanup remains Account-owned and must prove its retained recovery/replay horizon, holds and references before deletion; expiry alone is not deletion proof and no fixed retention interval is invented here. The current candidate composes this Account-local producer and immutable receipt; it does not implement downstream event delivery, authenticated recipient readback, projection consumption, or active-binding termination. The capability and execution gates remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 74c6f77e4b..9a006dbecf 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -12,6 +12,18 @@ The canonical `authorityTuple` schema, exact nested field names, profile require Authentication applies the canonical `authorityTuple` unchanged to admission and authorization where the selected profile or artifact requires it. Account-owned generation/projection rules, route-class exceptions, and token-registry semantics remain canonical in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md) and [Authorization Route Matrix](./system-architecture-authz-route-matrix.md); `membershipVersion` is separate membership-version evidence and never substitutes for the `membershipAuthorityGeneration` member of `authorityTuple`. +### Authority Source Events And Recipient Evidence + +Issuer-wide, account-wide, and tenant-wide publisher events use distinct closed, versioned source schemas. Each binds its exact source scope, committed generation and source version, stream checkpoint, event ID, and digest. Account commits the source mutation, scope advance, and outbox event atomically. These scope-wide source events are source evidence, not per-recipient Account authority snapshots, and do not carry a recipient-specific `issuanceFence` or complete recipient `authorityTuple`. + +For each recipient, an Account-authenticated readback binds the consumed source event and checkpoint to that recipient's complete applicable `authorityTuple`, Account's actual `issuanceFence`, and complete `outboxCheckpoints` set in one Account snapshot. Consumers compare this complete binding when advancing, bootstrapping, retrying, or accepting duplicates. The Account readback composes source and recipient evidence without a distributed transaction or per-recipient event fanout. This distinction does not alter the closed `account-auth-authority-event/v1` membership event schema below, including its declared tuple and fence fields. + +#### Account Password-Reset Source Event + +`account-auth-password-reset-event/v1` is the closed source schema for an Account-committed password-reset cutoff. Its required fields are `schemaVersion` (exactly `account-auth-password-reset-event/v1`), `eventType` (exactly `PASSWORD_RESET_COMMITTED`), `eventId`, `requestId`, `accountId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `accountAuthorityGeneration`, `sourceVersion`, and `accountSecurityCutoff`; its sole additional wire field is `eventDigest`. The `accountId` is a canonical lowercase non-nil UUID, `sourceScope` is exactly `account/`, and `outboxStreamKey` is exactly `account:auth-authority:v1:`. `eventId` and `requestId` are nonempty immutable operation identities. `accountSecurityCutoff` has exactly `accountAuthorityGeneration`, `outboxStreamKey`, and `outboxSequence`, equal to those source-event fields. Every generation, source version, and sequence is a canonical positive decimal string, including nested values; consumers parse arbitrary precision without floating-point conversion. There are no optional fields, arrays, `null` placeholders, raw credentials, password verifiers, or recipient tuple/fence fields in this schema. + +The digest preimage is the entire declared event object excluding **only** `eventDigest`, serialized as RFC 8785 canonical JSON UTF-8. `eventDigest` is `sha256:` plus 64 lowercase hexadecimal SHA-256 digits. Receivers reject duplicate properties, unknown/missing fields, noncanonical scope/counters, mismatched cutoff evidence, and a changed field paired with the original digest. Account stores the complete canonical event with the password mutation, token consumption, source generation/version and applicable local fence advance in one transaction. The separate Account-authenticated recipient snapshot binds this event to current recipient evidence; the event never creates gameplay admission. [Account API Contracts](./microservices/account-service/api-contracts.md) owns reset operation identity and exact-result retry. Other Account change types, issuer cutoffs and tenant billing changes require their own declared closed schemas before emission; this password-reset schema must not be aliased or fabricated for them. + ### Playtest Grant Admission Consequence Account's explicit grant record, bounded expiry, revision/request replay, tombstone, tenant-admin authority, and audited platform-admin break-glass mutation path are canonical in [Account API Contracts](./microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Authentication owns only the caller-bound consequence: private/playtest discovery, connect-token issuance, `PLAY`, reconnect, and continued gameplay require the current Account grant in addition to `ACTIVE` membership, entitlement, and exact routing evidence. Effective expiry or revocation is an immediate authority cutoff, not a grace period; Game Session consumes Account's bounded authority change and terminates affected bindings. A friendly scheduled ending uses the separate close-and-drain lifecycle before grant revocation. No JWT role, cached discovery result, or grant projection creates gameplay authority by itself. @@ -37,7 +49,8 @@ For every private/playtest grant consequence, the exact Account target is `{acco - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. - The current Account `Authenticate` proto path still lacks the target `requestId`/immutable-digest replay envelope and orphan-token retirement contract described below; those fields and recovery semantics remain implementation/proof gaps rather than implied current behavior. - **Current reauthentication boundary:** After a gameplay binding is terminated by an authority cutoff or the bounded cleanup path, current restoration requires fresh `LOGIN` plus `PLAY` and current authoritative checks. Token refresh, replacement, revocation, fencing, and logout are owned by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md); gameplay binding continuity, reconnect, and resume orchestration remain in [Session Behavior](./system-architecture-session-behavior.md). Fresh `LOGIN` then `PLAY` remains the client-visible reauthentication path when required. -- Account's JWKS endpoint and conditional secret watcher are implemented, but asymmetric-profile validation, non-exportable signer delegation for asymmetric signing, rotation/convergence, issued-token registry issuance/storage/consumer enforcement, and Account-owned authority generations remain target-state and unimplemented. No authority-generation issuance, advancement, propagation, or validation proof is currently claimed. +- Account's JWKS endpoint and conditional secret watcher are implemented, while complete asymmetric-profile enforcement, non-exportable signer delegation for asymmetric signing, rotation/convergence and issued-token registry issuance/storage/consumer enforcement remain open. Account-local durable generations, outbox and source-operation components exist; their scoped implementation and execution proof are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md), not claimed as complete credential issuance, distributed propagation or current-authority consumption. +- **Scoped authority-source runtime status:** The current Account password-reset candidate composes a closed source event, atomic Account mutation, generation/fence advance and immutable retry receipt. This Account-local slice does not complete issuer/tenant publishers, Account-authenticated same-snapshot recipient readback, delivery or Game Session consumption; authority-event consumer activation remains closed. Execution evidence and remaining producer/consumer obligations are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). ## Contract Decisions (Normative) @@ -49,7 +62,7 @@ For the closed `account-auth-authority-event/v1` membership event, `membershipVe - **Issuer projection checkpoint** – The Redis issuer-generation projections use `lastAppliedSourceOutboxSequence`, `lastAppliedSourceEventId`, and `lastAppliedSourceEventDigest` for the exact Account authority outbox stream. Sequence `0` is permitted only when that stream has no committed event; at that baseline, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, never serialized as `null`, an empty string, a zero digest, or another sentinel. For every positive sequence, both source-event fields are required non-null values in their canonical formats, and the projection advances only on the next contiguous sequence after exact checkpoint validation. These are projection-local replay/checkpoint fields, not JWT claims; JWT claims carry only the applicable authority tuple, including `issuerAuthGeneration`. - **Authority outbox stream** – Account emits each revocation payload on exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound playtest grant scope produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep watermarks per exact stream key: duplicates with matching evidence at or below the watermark are no-ops, the next sequence is contiguous, a higher sequence is a gap only within that same key, and an unrelated scope never creates a gap. Conflicting duplicate evidence or a same-key gap stops affected validation/admission until Account reconciliation proves the exact checkpoint. - **Playtest grant stream identity** – The grant stream's scope, `sourceScope`, and `outboxStreamKey` are lifecycle-bound and must be produced and parsed only by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Any grant revision, tombstone, lookup, or admission evidence that omits `playtestLifecycleId` is incomplete and fails closed; a realm slug alone cannot select a grant. -- **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; each retained entry includes `eventId`, the canonical event digest, `sourceScope`, the complete applicable `authorityTuple`/`issuanceFence`, and the relevant event payload evidence. When a duplicate at or below the watermark falls outside that window, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)` and compare the supplied evidence for exact equality. Matching evidence is accepted as a no-op; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed; reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. +- **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; retained source evidence preserves each event's exact identity, digest, scope, and payload under its owning closed schema. When an event is used as recipient authority evidence, Account-authenticated readback separately binds its source checkpoint to the complete applicable `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one Account snapshot. A duplicate at or below the watermark is accepted only when its source evidence matches exactly and, where recipient authority applies, the complete Account binding also matches. If retained source evidence is unavailable, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)`; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed, while reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. - **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is exactly `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: }`. Separate same-snapshot source evidence binds event ID and canonical digest to that checkpoint, tuple, issuance fence, and complete checkpoint set under [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint has no event ID or digest, grants no admission, and is followed by the first committed `JOIN` event at sequence `1`. A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. - **Never-joined pair baseline** – For each verified account/tenant pair, Account owns a durable pair-authority record with a positive membership generation and independent positive membership version even while membership is absent. A sequence-zero response requires one Account-fenced snapshot that proves this exact record, the verified pair identity, no current membership, and no committed membership event or retained contradictory history; absence of a row alone is never a generation, version, or checkpoint. The first explicit `JOIN` commits event sequence `1` and advances `membershipVersion` from that recorded absence baseline. It advances `membershipAuthorityGeneration` independently only if the transition records `callerBoundAuthorityInvalidated=true`. Existing retained membership versions and positive event sequences are preserved rather than assigned a synthetic absence baseline or renumbered. Unmapped or contradictory pairs remain denied, and sequence zero never authorizes admission. - **Membership event continuity** – Membership changes use only `account:auth-authority:v1:membership//`. Each event names `outboxStreamKey`, `sourceScope` (`membership//`), `outboxSequence`, `eventId`, the complete applicable `authorityTuple`/`issuanceFence`, and the Account snapshot's `accountId`, `tenantId`, `membershipVersion`, membership payload, admission flag, and `callerBoundAuthorityInvalidated` result. `sourceScope` must decode to `outboxStreamKey`; each consumer stores a `watermark` and event identity/digest per exact stream and marks delivery `contiguous` only when the next sequence is `watermark + 1` (with first-stream initialization from the Account checkpoint). A duplicate at or below the watermark is valid only when all evidence matches; a same-sequence conflict quarantines the affected scope. A higher sequence is a gap only within that same stream; unrelated streams do not advance or gap this watermark. Conflicts, non-contiguous delivery, missing or mismatched tuple/checkpoint evidence, or an unresolved membership-version/generation pair stop affected admission and reconnect/validation until exact Account reconciliation proves coverage; unavailable reconciliation returns retryable `AUTH_UNAVAILABLE`, while reachable contradictory or revoked evidence is denied/revoked. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index d8d336ee8f..f69e5a8641 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -10,7 +10,7 @@ Each registry-backed revocable `control-ui`, `player-bootstrap`, or receiver-spe ## Canonical Authority Tuple -Every registry-backed JWT claim set, registry record, revocation event, Account lease, gameplay binding, refresh request, rebind proof, and installation acknowledgement uses the same logical `authorityTuple` and exact field names: +Every registry-backed JWT claim set, registry record, recipient-bound revocation evidence carrier, Account lease, gameplay binding, refresh request, rebind proof, and installation acknowledgement uses the same logical `authorityTuple` and exact field names: ```text authorityTuple: { @@ -45,6 +45,8 @@ The pre-v1 grant cutover is direct: a JWT, issued-token registry record, authori The tuple is copied without renaming or reinterpretation into every applicable registry-backed JWT/registry claim, payload, lease, binding, refresh request, rebind proof, and installation acknowledgement. `issuanceFence` is copied alongside the tuple as the Account composite authority fence captured by the issuance transaction or CAS; it is not a substitute for any tuple member. +Publisher source events and recipient authority evidence are distinct under [Authentication's source-event boundary](./system-architecture-authentication.md#authority-source-events-and-recipient-evidence). An issuer-wide or tenant-wide source event binds its own committed scope generation/source version and exact stream event/checkpoint, not an arbitrary recipient Account's tuple or issuance fence. Account-authenticated recipient readback binds that source evidence to the complete applicable tuple, actual recipient issuance fence, and complete checkpoint set in one Account snapshot. These source schemas do not alter this JWT/registry tuple or exempt a recipient from complete current-authority validation. + `membershipVersion` is separate from `authorityTuple` and is a required map in each profile schema: when membership is non-applicable its canonical value is `{}`, never omission, `null`, a scalar, or a sentinel. For Account's `GetTenantMembershipForRuntime` response and persisted or cross-service gameplay carriers, an applicable `membershipVersion` is the exact one-tenant map `{tenantId: version}`. Across the JWT claim, registry record, Account evidence bundle, and each applicable lease, binding, rebind, rotation, installation, and retry carrier, the complete map structure and key/value pairs must remain exactly equal. A receiver may extract a scalar for process-local calculations only after validating that map; it must not transmit or persist the scalar as `membershipVersion`. The map remains an independent predicate from `authorityTuple.membershipAuthorityGeneration`, which must also be compared exactly; neither value may be inferred from or substituted for the other. For the `gameplay-connect` token and `X-Firemud-Connect-Context`, Account derives the caller-bound `authorityTuple.membershipAuthorityGeneration` and the separate `membershipVersion` map from the same authoritative membership snapshot for the exact selected tenant. They remain independent predicates and neither may be reconstructed from the other, a cached projection, or a later read. Before continuation, including reconnect/resume, Game Session must compare both values together against one fresh Account membership snapshot; if either comparison cannot be established from that snapshot, continuation fails closed. @@ -142,7 +144,7 @@ For the selected `player_bootstrap_tenant` route metadata, `IssueConnectToken` m Authority-generation contract requirements: - Account Service owns durable current generations and is the sole writer of their Coordination Redis projections. -- Account advances every applicable durable field in `authorityTuple`, applicable cutoff, and `issuanceFence` in the same transaction as the authority change and commits the monotonic outbox event. The `session:auth:generation:*` projection is an asynchronous outbox consumer output, not an atomically committed part of that durable generation/event transaction. Projection is idempotent set-if-greater and cannot regress; consumers fail closed while the projection or its freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. +- Account commits each authority-source mutation, exact scope generation/source-version advance, applicable cutoff, and scoped outbox event in one Account transaction. An account-local issuance fence advances only for a mutation whose Account scope requires it; issuer-wide and tenant-wide writers serialize on their own source scopes without per-account fanout or fabricating a recipient fence. Issuance and recipient readback still lock or compare every applicable source scope and the actual Account issuance fence at one Account linearization point. The [Authentication source/recipient boundary](./system-architecture-authentication.md#authority-source-events-and-recipient-evidence) governs that distinction. The `session:auth:generation:*` projection is an asynchronous outbox consumer output, not an atomically committed part of that durable generation/event transaction. Projection is idempotent set-if-greater and cannot regress; consumers fail closed while the projection or its freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. - The authority outbox stream key is exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound non-public grant scope for ordinary-private and playtest grants produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep a watermark per exact stream key: an event at or below that watermark is accepted as an idempotent duplicate only when its exact event identity and digest match retained evidence or an exact Account lookup, without requiring a contiguous-sequence check. A high-water mark alone is never duplicate proof. When bounded evidence for a lower-sequence event has aged out, the consumer must perform an exact Account lookup keyed by the same `outboxStreamKey` and `outboxSequence`; it must not accept the replay from the watermark alone. That lookup must prove the same event identity, digest, applicable authority values, `issuanceFence`, and source checkpoint. Missing, stale, malformed, conflicting, ambiguous, or unavailable lookup evidence keeps the affected scope quarantined and returns retryable `AUTH_UNAVAILABLE` where appropriate. A new event above the watermark must equal `watermark + 1`; a higher sequence is a gap only within that same stream. An unrelated scope never creates a gap. A same-key gap or conflicting duplicate stops affected admission/validation until Account reconciliation proves checkpoint coverage. - Focused reconciliation for an aged-out lower-sequence replay records the exact stream key and sequence, prior watermark, event identity and digest, applicable authority tuple and `issuanceFence`, Account source transaction or outbox checkpoint, projection freshness/status, and the reconciliation operation identity. Admission or validation resumes only after that evidence proves the exact event is covered by the same Account authority scope and the consumer has durably recorded the matching duplicate evidence or repaired checkpoint; a high-water mark, aggregate maximum, or unrelated stream checkpoint cannot resume the scope. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5ec5fec467..f526f9be7a 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -212,3 +212,7 @@ Entry format: - Context: a bounded CI investigation authorized only the named Game Session artifact in a fresh `mktemp` directory. The helper instead invoked an unfiltered download into `/tmp/not-used`, receiving three unrelated coverage artifact folders, then removed that directory without proving it was absent before the command. No repository files changed; the helper reported only the three downloaded coverage folders were present, but prior exclusivity was not established. - Consequence: neither unrelated artifacts nor inferred prior directory ownership supplies valid diagnostic evidence. The directory was removed; its earlier state cannot be established from that inspection. Root stopped further cleanup and restricted the continuation to a new exclusive directory and the exact named artifact. - Expected pattern: use an artifact-name filter and a freshly created exclusive temporary directory, separate read-only evidence retrieval from cleanup, and never recursively delete a generic output directory merely because a preceding tool wrote into it. Report a scope violation before recovery; do not broaden a read-only task with unapproved cleanup. + +- `2026-10-02`: Do not use a truncated PR file array as the changed-file count + - Context: `gh pr view --json files` returned 100 entries for the coherent Unit 1B carrier, while the GitHub `changedFiles` scalar and the exact local base/head diff both reported 116. Counting the returned array alone would have understated the published scope. + - Expected pattern: use the PR's `changedFiles` scalar for scope counts and independently compare the exact base/head diff; when individual paths are needed, retrieve the complete paginated list rather than treating a capped array as full coverage. A truncated array is not evidence that the patch fits a reviewer ceiling. 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 85bf514186..78c407ae3d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. Issuer-wide source-only projection evidence remains a distinct pending authority clarification and is not implemented by this Account-local producer. + The unpublished Game Session Account-UUID carrier now incorporates #2929's reconciled grant-containment checkpoint `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3` through normal ancestry. Its corrected fake Account and Entity services preserve explicit Account UUIDs; synthetic load actors use registered UUID-to-character associations, not numeric Account aliases. FRIENDS direct selectors are UUIDs while roster ordinals and character/session/tenant selectors stay distinct. Negative fixture tests reject numeric, noncanonical, nil and null Account selectors without changing valid profile readback. The unique scope is115files and remains unpublished pending cap treatment. The earlier corrected-fixture shared-support/Game Session/TCP checks and both affected JARs passed189tasks(64executed/125up-to-date). Shared44unit and TCP194unit/7integration/3cross-service cases executed cleanly; Game Session18non-PostgreSQL integration and1cross-service executed cleanly, while its1,773unit results were up-to-date from the preceding same-code run. Game Session skipped17unit/135integration/33cross-service cases; TCP skipped14cross-service cases without Docker. No skipped case proves positive cross-service admission. The existing synthetic numeric tenant fixture is not owner provenance or a complete authenticated snapshot. Production Game Logic/Social numeric sender authority/storage and Entity's numeric actor-owner lookup are separate remaining consumer/data boundaries, not fixed by these fixtures. Runtime activation and section completion remain denied. Final composed Account/Game Session/TCP/shared-support checks, all three service JARs and docs passed218tasks(27executed/4from-cache/187up-to-date). Account517unit cases newly executed cleanly, while all161Account PostgreSQL cases skipped and other modules' test tasks were up-to-date. Stable patch ID `3c1e7ccb70b1f8256a70044afbcb90e2a7acd885` is unchanged for the entire unique services/protos patch across the parent merge; only the seven incoming correction paths change from the preceding carrier. Earlier merge/proof reports below are historical checkpoints. The local gameplay Account-UUID carrier now normally incorporates corrected published #2929 `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6`, including the username-bound and typed JDBC UUID fixture corrections. Composed Account/Game Session/shared-support checks, both JARs and documentation passed163tasks(18executed/145up-to-date). The preceding same-code Game Session executions remain1,773unit,18non-PostgreSQL integration and1cross-service without failures/errors; final test tasks were up-to-date rather than new executions. Account PostgreSQL and Game Session PostgreSQL/cross-service skips remain explicit. The exact corrected parent runner proof is pending. The child remains108unique files and unpublished; neither reconciliation nor cached/up-to-date results establish runtime activation or section completion. The following earlier parent merges and proof reports are chronological history. diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 1a362013eb..b6d248d0f0 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -15,4 +15,6 @@ dependencies { implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + // Integration analysis follows the real producer's annotated Account collaborators. + add("integrationTestImplementation", "com.github.spotbugs:spotbugs-annotations:4.9.8") } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java new file mode 100644 index 0000000000..700668e747 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java @@ -0,0 +1,316 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stores immutable proof for one Account-owned password-reset source commit. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountPasswordResetOperationRepository { + private static final String TABLE = "account_password_reset_operation_receipts"; + private static final String REQUEST_ID_PREFIX = "account-password-reset-request-v1:"; + private static final String EVENT_ID_PREFIX = "account-password-reset-event-v1:"; + private static final String SELECT_COLUMNS = + "token_hash, account_id, account_uuid, operation_kind, request_id, " + + "request_digest_version, request_digest, token_expires_at, " + + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, " + + "event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + + public AccountPasswordResetOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Read-only lookup by the SHA-256 identity of the token, including after token consumption. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByTokenHash(String tokenHash) { + requireOwnerTransaction(); + byte[] tokenHashBytes = decodeDigest(tokenHash, "token hash"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE token_hash = ?", + tokenHashBytes); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Read-only source-history lookup used to prove a progressed Account stream. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByRequestId(String requestId) { + requireOwnerTransaction(); + requireBoundedText(requestId, "request ID", 128); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable receipt for this token hash. */ + @Transactional(propagation = Propagation.MANDATORY) + public PasswordResetReceipt insert(PasswordResetReceipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (token_hash, account_id, account_uuid, operation_kind, request_id, " + + "request_digest_version, request_digest, token_expires_at, " + + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, " + + "event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version) " + + "VALUES (?, ?, ?, 'PASSWORD_RESET', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + decodeDigest(receipt.tokenHash(), "token hash"), + receipt.accountId(), + receipt.accountUuid(), + receipt.requestId(), + decodeDigest(receipt.requestDigest(), "request digest"), + receipt.tokenExpiresAt(), + decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + receipt.eventDigest(), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + if (inserted != 1) { + throw new IllegalStateException("Password-reset operation receipt was not inserted"); + } + return receipt; + } + + private PasswordResetReceipt toReceipt(Record row) { + return new PasswordResetReceipt( + requiredPositive(row.get("account_id", Long.class), "Account association"), + Objects.requireNonNull(row.get("account_uuid", UUID.class), "receipt Account UUID"), + encodeDigest(row.get("token_hash", byte[].class), "token hash"), + requireText(row.get("operation_kind", String.class), "operation kind"), + requireText(row.get("request_id", String.class), "request ID"), + requiredPositive(row.get("request_digest_version", Integer.class), "digest version"), + encodeDigest(row.get("request_digest", byte[].class), "request digest"), + Objects.requireNonNull( + row.get("token_expires_at", java.time.LocalDateTime.class), "token deadline"), + encodeDigest(row.get("password_verifier_digest", byte[].class), "password verifier digest"), + requireText(row.get("outbox_stream_key", String.class), "outbox stream key"), + requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"), + requireText(row.get("event_id", String.class), "event ID"), + requireText(row.get("event_digest", String.class), "event digest"), + requiredPositive( + row.get("account_authority_generation", Long.class), "Account authority generation"), + requiredPositive(row.get("account_source_version", Long.class), "Account source version"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive( + row.get("issuance_fence_source_version", Long.class), "issuance-fence source version")); + } + + private static void validateReceipt(PasswordResetReceipt receipt) { + Objects.requireNonNull(receipt, "password-reset receipt is required"); + decodeDigest(receipt.tokenHash(), "token hash"); + decodeDigest(receipt.requestDigest(), "request digest"); + decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"); + if (receipt.accountId() <= 0L + || receipt.accountUuid() == null + || new UUID(0L, 0L).equals(receipt.accountUuid()) + || receipt.requestDigestVersion() != 1 + || receipt.tokenExpiresAt() == null + || receipt.outboxSequence() <= 0L + || receipt.accountAuthorityGeneration() <= 0L + || receipt.accountSourceVersion() <= 0L + || receipt.issuanceFence() <= 0L + || receipt.issuanceFenceSourceVersion() <= 0L + || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey()) + || receipt.eventDigest() == null + || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset operation receipt is malformed"); + } + requireBoundedText(receipt.operationKind(), "operation kind", 32); + if (!"PASSWORD_RESET".equals(receipt.operationKind())) { + throw new IllegalArgumentException("Password-reset operation kind is invalid"); + } + requireBoundedText(receipt.requestId(), "request ID", 128); + requireBoundedText(receipt.eventId(), "event ID", 128); + if (!(REQUEST_ID_PREFIX + receipt.tokenHash()).equals(receipt.requestId()) + || !(EVENT_ID_PREFIX + receipt.tokenHash()).equals(receipt.eventId())) { + throw new IllegalArgumentException( + "Password-reset operation IDs must be derived from the token hash"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Password-reset operation storage requires an active Account transaction"); + } + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static String requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static void requireBoundedText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Password-reset receipt " + + field + + " must contain 1 to " + + maximumLength + + " characters"); + } + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset receipt " + field + " is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return HEX.formatHex(value); + } + + private static String accountStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + /** Immutable commit and retry evidence; digest values are lowercase SHA-256 hex strings. */ + public record PasswordResetReceipt( + long accountId, + UUID accountUuid, + String tokenHash, + String operationKind, + String requestId, + int requestDigestVersion, + String requestDigest, + java.time.LocalDateTime tokenExpiresAt, + String passwordVerifierDigest, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + long accountAuthorityGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion) { + public PasswordResetReceipt { + decodeDigest(tokenHash, "token hash"); + decodeDigest(requestDigest, "request digest"); + decodeDigest(passwordVerifierDigest, "password verifier digest"); + if (accountId <= 0L + || accountUuid == null + || new UUID(0L, 0L).equals(accountUuid) + || requestDigestVersion != 1 + || tokenExpiresAt == null + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || !accountStreamKey(accountUuid).equals(outboxStreamKey) + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset operation receipt is malformed"); + } + requireBoundedText(operationKind, "operation kind", 32); + if (!"PASSWORD_RESET".equals(operationKind)) { + throw new IllegalArgumentException("Password-reset operation kind is invalid"); + } + requireBoundedText(requestId, "request ID", 128); + requireBoundedText(eventId, "event ID", 128); + if (!(REQUEST_ID_PREFIX + tokenHash).equals(requestId) + || !(EVENT_ID_PREFIX + tokenHash).equals(eventId)) { + throw new IllegalArgumentException( + "Password-reset operation IDs must be derived from the token hash"); + } + } + + public static PasswordResetReceipt committed( + long accountId, + UUID accountUuid, + String tokenHash, + String requestId, + String requestDigest, + java.time.LocalDateTime tokenExpiresAt, + String passwordVerifierDigest, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + ScopeState accountAuthority, + IssuanceFence issuanceFence) { + if (accountAuthority == null + || issuanceFence == null + || accountAuthority.issuanceFence() == null + || !issuanceFence.equals(accountAuthority.issuanceFence())) { + throw new IllegalArgumentException( + "Committed password-reset authority and issuance fence must match exactly"); + } + return new PasswordResetReceipt( + accountId, + accountUuid, + tokenHash, + "PASSWORD_RESET", + requestId, + 1, + requestDigest, + tokenExpiresAt, + passwordVerifierDigest, + outboxStreamKey, + outboxSequence, + eventId, + eventDigest, + accountAuthority.generation(), + accountAuthority.sourceVersion(), + issuanceFence.value(), + issuanceFence.sourceVersion()); + } + + public IssuanceFence issuanceFenceEvidence() { + return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion); + } + } + + /** A token identity was already committed with a different supplied password. */ + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index b1002a2489..3e30ad7734 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -29,6 +29,15 @@ public Optional findById(Long id) { dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity)); } + /** Locks and rereads the complete persisted Account identity and credential source row. */ + public Optional findByIdForUpdate(Long id) { + if (id == null || id <= 0L) { + throw new IllegalArgumentException("A positive Account row identity is required"); + } + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity)); + } + public Optional findByAccountUuid(UUID accountUuid) { Objects.requireNonNull(accountUuid, "accountUuid must not be null"); return Optional.ofNullable( @@ -111,6 +120,41 @@ public Account save(Account entity) { return entity; } + /** Replaces the password verifier only while the caller still owns the exact locked Account. */ + public Account updatePasswordHashForLockedAccount(Account expected, String passwordHash) { + if (expected == null + || expected.getId() == null + || expected.getAccountUuid() == null + || expected.getAccountUuidProvenance() == null + || expected.getAccountUuidSourceNumericId() == null + || passwordHash == null + || passwordHash.isBlank()) { + throw new IllegalArgumentException( + "A locked Account identity and password verifier are required"); + } + AccountsRecord updated = + dsl.update(ACCOUNTS) + .set(ACCOUNTS.PASSWORD_HASH, passwordHash) + .where(ACCOUNTS.ID.eq(expected.getId())) + .and(ACCOUNTS.ACCOUNT_UUID.eq(expected.getAccountUuid())) + .and(ACCOUNTS.ACCOUNT_UUID_PROVENANCE.eq(expected.getAccountUuidProvenance().name())) + .and( + ACCOUNTS.ACCOUNT_UUID_SOURCE_NUMERIC_ID.eq( + expected.getAccountUuidSourceNumericId())) + .and(ACCOUNTS.PASSWORD_HASH.isNotDistinctFrom(expected.getPasswordHash())) + .returning() + .fetchOne(); + if (updated == null) { + throw JooqAccountRepositorySupport.staleWrite("accounts", expected.getId()); + } + requireExactIdentityReadback( + updated, expected.getAccountUuid(), expected.getAccountUuidProvenance()); + if (!Objects.equals(updated.getPasswordHash(), passwordHash)) { + throw new IllegalStateException("Account password verifier readback did not match its write"); + } + return toEntity(updated); + } + public void delete(Account entity) { if (entity != null && entity.getId() != null) { dsl.deleteFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(entity.getId())).execute(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java index 38ede92a17..6208c8149c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java @@ -72,7 +72,8 @@ public boolean consumeIfUnexpired(PasswordResetToken token, LocalDateTime captur .ID .eq(token.getId()) .and(PASSWORD_RESET_TOKEN.TOKEN.eq(token.getToken())) - .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.ge(capturedNow))) + .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.eq(token.getExpiresAt())) + .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.gt(capturedNow))) .execute() == 1; } 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 76af557103..c5866b2a85 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 @@ -6,6 +6,7 @@ import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import io.micrometer.core.annotation.Timed; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -15,6 +16,7 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; @@ -69,12 +71,19 @@ import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -95,6 +104,8 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; @@ -127,6 +138,11 @@ public class AccountServiceImpl implements AccountService { "Join the selected world before discovering characters"; public static final String ACCOUNT_JWT_ISSUER = "firemud-account-service"; private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; + private static final String PASSWORD_RESET_OPERATION_KIND = "PASSWORD_RESET"; + private static final String PASSWORD_RESET_REQUEST_DOMAIN = "account-password-reset-request/v1"; + private static final String PASSWORD_RESET_REQUEST_ID_PREFIX = + "account-password-reset-request-v1:"; + private static final String PASSWORD_RESET_EVENT_ID_PREFIX = "account-password-reset-event-v1:"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); @@ -134,6 +150,8 @@ public class AccountServiceImpl implements AccountService { private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; + private final AccountAuthorityOutboxRepository accountAuthorityOutboxRepository; + private final AccountPasswordResetOperationRepository passwordResetOperationRepository; private final AccountAuditOutboxRepository accountAuditOutboxRepository; private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; @@ -169,6 +187,8 @@ public class AccountServiceImpl implements AccountService { public AccountServiceImpl( AccountRepository accountRepository, AccountAuthorityGenerationRepository accountAuthorityGenerationRepository, + AccountAuthorityOutboxRepository accountAuthorityOutboxRepository, + AccountPasswordResetOperationRepository passwordResetOperationRepository, AccountAuditOutboxRepository accountAuditOutboxRepository, AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, @@ -198,6 +218,8 @@ public AccountServiceImpl( PlatformTransactionManager transactionManager) { this.accountRepository = accountRepository; this.accountAuthorityGenerationRepository = accountAuthorityGenerationRepository; + this.accountAuthorityOutboxRepository = accountAuthorityOutboxRepository; + this.passwordResetOperationRepository = passwordResetOperationRepository; this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; @@ -2226,20 +2248,544 @@ public void requestPasswordReset(PasswordResetRequest request) { @Transactional @Timed(value = "account.complete_password_reset") public void completePasswordReset(CompletePasswordResetRequest request) { + if (request == null + || request.token() == null + || request.token().isBlank() + || request.newPassword() == null) { + throw new IllegalArgumentException("Password-reset token and new password are required"); + } + + String tokenHash = sha256Hex(request.token()); + Optional resolvedReceipt = + passwordResetOperationRepository.findByTokenHash(tokenHash); + Optional resolvedToken = + resolvedReceipt.isPresent() + ? Optional.empty() + : passwordResetTokenRepository.findByToken(request.token()); + Long accountId = + resolvedReceipt + .map(PasswordResetReceipt::accountId) + .orElseGet( + () -> + resolvedToken + .map( + token -> token.getAccount() == null ? null : token.getAccount().getId()) + .orElse(null)); + if (accountId == null || accountId <= 0L) { + throw new IllegalArgumentException("Invalid token"); + } + + Account account = + accountRepository + .findByIdForUpdate(accountId) + .orElseThrow(() -> new IllegalArgumentException("Invalid token")); + requireAuthenticationPersistedIdentity(account); + + Optional lockedReceipt = + passwordResetOperationRepository.findByTokenHash(tokenHash); + if (lockedReceipt.isPresent()) { + PasswordResetReceipt receipt = lockedReceipt.get(); + requireReceiptAccountBinding(receipt, account); + completePasswordResetRetry(account, receipt, request, tokenHash); + return; + } + if (resolvedReceipt.isPresent()) { + throw new IllegalStateException( + "Password-reset receipt changed while its Account was locked"); + } + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = passwordResetTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); + requireTokenAccountBinding(token, account); + if (resolvedToken.isEmpty() + || !Objects.equals(resolvedToken.get().getId(), token.getId()) + || !Objects.equals(resolvedToken.get().getExpiresAt(), token.getExpiresAt())) { + throw new IllegalStateException("Password-reset token changed while its Account was locked"); + } + LocalDateTime now = LocalDateTime.now(); - if (token.getExpiresAt().isBefore(now)) { + if (token.getExpiresAt() == null || !token.getExpiresAt().isAfter(now)) { throw new IllegalArgumentException("Token expired"); } - if (!passwordResetTokenRepository.consumeIfUnexpired(token, now)) { + + AuthorityScope accountScope = AuthorityScope.account(account.getAccountUuid()); + ScopeState currentAuthority = readPasswordResetAccountAuthority(accountScope); + requireProvenPasswordResetSource(account, currentAuthority); + + String newPasswordVerifier = hashPassword(request.newPassword()); + String passwordVerifierDigest = sha256Hex(newPasswordVerifier); + String requestId = passwordResetRequestId(tokenHash); + String eventId = passwordResetEventId(tokenHash); + String requestDigest = + passwordResetRequestDigest( + account.getAccountUuid(), tokenHash, token.getExpiresAt(), passwordVerifierDigest); + + LocalDateTime claimTime = LocalDateTime.now(); + if (!token.getExpiresAt().isAfter(claimTime)) { + throw new IllegalArgumentException("Token expired"); + } + if (!passwordResetTokenRepository.consumeIfUnexpired(token, claimTime)) { throw new IllegalArgumentException("Invalid token"); } - net.firedevops.firemud.accountservice.entity.Account account = token.getAccount(); - account.setPasswordHash(hashPassword(request.newPassword())); - accountRepository.save(account); + Account passwordUpdated = + accountRepository.updatePasswordHashForLockedAccount(account, newPasswordVerifier); + requireAccountReadback(account, passwordUpdated, newPasswordVerifier); + + ScopeState advancedAuthority = + accountAuthorityGenerationRepository.advance( + currentAuthority, currentAuthority.issuanceFence()); + requireAdvancedPasswordResetAuthority(accountScope, currentAuthority, advancedAuthority); + + String streamKey = passwordResetStreamKey(account.getAccountUuid()); + Event appended = + accountAuthorityOutboxRepository.append( + streamKey, + requestId, + sequence -> + passwordResetEventEvidence( + account.getAccountUuid(), + requestId, + eventId, + sequence, + advancedAuthority.generation(), + advancedAuthority.sourceVersion())); + PasswordResetAuthorityEvent committedEvent = + requirePasswordResetEvent( + appended, + account.getAccountUuid(), + requestId, + eventId, + advancedAuthority.generation(), + advancedAuthority.sourceVersion()); + Checkpoint committedCheckpoint = + accountAuthorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Password-reset outbox checkpoint is missing")); + requireCheckpointMatches(committedCheckpoint, appended); + + PasswordResetReceipt receipt = + PasswordResetReceipt.committed( + account.getId(), + account.getAccountUuid(), + tokenHash, + requestId, + requestDigest, + token.getExpiresAt(), + passwordVerifierDigest, + streamKey, + appended.outboxSequence(), + committedEvent.eventId(), + committedEvent.eventDigest(), + advancedAuthority, + advancedAuthority.issuanceFence()); + passwordResetOperationRepository.insert(receipt); + + Account finalAccount = + accountRepository + .findByIdForUpdate(account.getId()) + .orElseThrow( + () -> new IllegalStateException("Password-reset Account readback is missing")); + requireAccountReadback(account, finalAccount, newPasswordVerifier); + ScopeState finalAuthority = readPasswordResetAccountAuthority(accountScope); + if (!advancedAuthority.equals(finalAuthority)) { + throw new IllegalStateException("Password-reset authority readback did not match its commit"); + } + Event eventReadback = + accountAuthorityOutboxRepository + .findEvent(streamKey, appended.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Password-reset event readback is missing")); + if (!appended.equals(eventReadback)) { + throw new IllegalStateException("Password-reset event readback did not match its commit"); + } + requirePasswordResetEvent( + eventReadback, + account.getAccountUuid(), + requestId, + eventId, + advancedAuthority.generation(), + advancedAuthority.sourceVersion()); + Checkpoint finalCheckpoint = + accountAuthorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Password-reset checkpoint readback is missing")); + requireCheckpointMatches(finalCheckpoint, eventReadback); + PasswordResetReceipt receiptReadback = + passwordResetOperationRepository + .findByTokenHash(tokenHash) + .orElseThrow( + () -> new IllegalStateException("Password-reset receipt readback is missing")); + if (!receipt.equals(receiptReadback)) { + throw new IllegalStateException("Password-reset receipt readback did not match its commit"); + } + if (passwordResetTokenRepository.findByToken(request.token()).isPresent()) { + throw new IllegalStateException("Consumed password-reset token remained readable"); + } + } + + private void completePasswordResetRetry( + Account account, + PasswordResetReceipt receipt, + CompletePasswordResetRequest request, + String tokenHash) { + LocalDateTime now = LocalDateTime.now(); + if (!receipt.tokenExpiresAt().isAfter(now)) { + throw new IllegalArgumentException("Token expired"); + } + requireReceiptAccountBinding(receipt, account); + String currentVerifier = account.getPasswordHash(); + if (currentVerifier == null || currentVerifier.isBlank()) { + throw new IllegalStateException("Password-reset result was superseded"); + } + String currentVerifierDigest = sha256Hex(currentVerifier); + if (!constantTimeTextEquals(currentVerifierDigest, receipt.passwordVerifierDigest())) { + throw new IllegalStateException("Password-reset result was superseded"); + } + if (!verifyPassword(request.newPassword(), currentVerifier)) { + throw new AccountPasswordResetOperationRepository.OperationConflictException( + "Password-reset token was already committed with a different password"); + } + requireReceiptRequestDigest(receipt); + if (!constantTimeTextEquals(receipt.tokenHash(), tokenHash)) { + throw new IllegalStateException("Password-reset receipt token identity changed"); + } + + AuthorityScope accountScope = AuthorityScope.account(account.getAccountUuid()); + ScopeState currentAuthority = readPasswordResetAccountAuthority(accountScope); + requireReceiptAuthorityIsCurrentOrEarlier(receipt, currentAuthority); + Event event = + accountAuthorityOutboxRepository + .findEvent(receipt.outboxStreamKey(), receipt.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Password-reset event readback is missing")); + requireReceiptEventBinding(receipt, event); + PasswordResetReceipt receiptReadback = + passwordResetOperationRepository + .findByTokenHash(tokenHash) + .orElseThrow( + () -> new IllegalStateException("Password-reset receipt readback is missing")); + if (!receipt.equals(receiptReadback)) { + throw new IllegalStateException("Password-reset receipt readback did not match its commit"); + } + if (!receipt.tokenExpiresAt().isAfter(LocalDateTime.now())) { + throw new IllegalArgumentException("Token expired"); + } + } + + private void requireProvenPasswordResetSource(Account account, ScopeState state) { + AuthorityScope expectedScope = AuthorityScope.account(account.getAccountUuid()); + if (!expectedScope.equals(state.scope()) + || state.generation() <= 0L + || state.sourceVersion() <= 0L) { + throw new IllegalStateException("Account password-reset source scope is missing or invalid"); + } + requirePositiveAccountFence(state.issuanceFence(), account.getAccountUuid()); + + String streamKey = passwordResetStreamKey(account.getAccountUuid()); + Optional checkpoint = accountAuthorityOutboxRepository.readCheckpoint(streamKey); + if (state.generation() == 1L && state.sourceVersion() == 1L) { + if (checkpoint.isPresent()) { + throw new IllegalStateException( + "Pristine Account password-reset source has contradictory event history"); + } + return; + } + if (state.generation() <= 1L || state.sourceVersion() <= 1L || checkpoint.isEmpty()) { + throw new IllegalStateException("Account password-reset source history is not proven"); + } + + Checkpoint latestCheckpoint = checkpoint.get(); + Event latestEvent = + accountAuthorityOutboxRepository + .findEvent(streamKey, latestCheckpoint.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Account password-reset source event is missing")); + requireCheckpointMatches(latestCheckpoint, latestEvent); + PasswordResetAuthorityEvent verified = + verifyPasswordResetEvent(latestEvent, account.getAccountUuid()); + if (!Long.toString(state.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(state.sourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account password-reset event does not match its progressed source state"); + } + PasswordResetReceipt priorReceipt = + passwordResetOperationRepository + .findByRequestId(latestEvent.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account password-reset event has no immutable operation receipt")); + requireReceiptAccountBinding(priorReceipt, account); + requireReceiptEventBinding(priorReceipt, latestEvent); + requireReceiptAuthorityMatchesCurrent(priorReceipt, state); + String currentVerifier = account.getPasswordHash(); + if (currentVerifier == null + || !constantTimeTextEquals( + sha256Hex(currentVerifier), priorReceipt.passwordVerifierDigest())) { + throw new IllegalStateException( + "Latest Account password-reset event does not match the current password verifier"); + } + } + + private ScopeState readPasswordResetAccountAuthority(AuthorityScope accountScope) { + ScopeState state = accountAuthorityGenerationRepository.read(accountScope); + if (!accountScope.equals(state.scope())) { + throw new IllegalStateException("Account password-reset authority scope changed"); + } + requirePositiveAccountFence(state.issuanceFence(), accountScope.accountId()); + return state; + } + + private void requirePositiveAccountFence( + AccountAuthorityGenerationRepository.IssuanceFence fence, UUID accountUuid) { + if (fence == null + || !accountUuid.equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L) { + throw new IllegalStateException( + "Account password-reset issuance fence is missing or invalid"); + } + } + + private void requireAdvancedPasswordResetAuthority( + AuthorityScope expectedScope, ScopeState previous, ScopeState advanced) { + if (advanced == null + || !expectedScope.equals(advanced.scope()) + || advanced.generation() != Math.addExact(previous.generation(), 1L) + || advanced.sourceVersion() != Math.addExact(previous.sourceVersion(), 1L)) { + throw new IllegalStateException( + "Account password-reset authority did not advance exactly once"); + } + requirePositiveAccountFence(advanced.issuanceFence(), expectedScope.accountId()); + if (advanced.issuanceFence().value() != Math.addExact(previous.issuanceFence().value(), 1L) + || advanced.issuanceFence().sourceVersion() + != Math.addExact(previous.issuanceFence().sourceVersion(), 1L)) { + throw new IllegalStateException( + "Account password-reset issuance fence did not advance exactly once"); + } + } + + private void requireReceiptAccountBinding(PasswordResetReceipt receipt, Account account) { + if (receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !passwordResetStreamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey())) { + throw new IllegalStateException( + "Password-reset receipt does not match its Account source row"); + } + requireReceiptRequestDigest(receipt); + } + + private void requireReceiptRequestDigest(PasswordResetReceipt receipt) { + String expected = + passwordResetRequestDigest( + receipt.accountUuid(), + receipt.tokenHash(), + receipt.tokenExpiresAt(), + receipt.passwordVerifierDigest()); + if (receipt.requestDigestVersion() != 1 + || !PASSWORD_RESET_OPERATION_KIND.equals(receipt.operationKind()) + || !passwordResetRequestId(receipt.tokenHash()).equals(receipt.requestId()) + || !constantTimeTextEquals(expected, receipt.requestDigest())) { + throw new IllegalStateException("Password-reset receipt request evidence is inconsistent"); + } + } + + private void requireReceiptEventBinding(PasswordResetReceipt receipt, Event event) { + PasswordResetAuthorityEvent verified = verifyPasswordResetEvent(event, receipt.accountUuid()); + if (!receipt.outboxStreamKey().equals(event.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !passwordResetEventId(receipt.tokenHash()).equals(event.eventId()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException("Password-reset receipt does not match its source event"); + } + } + + private void requireReceiptAuthorityMatchesCurrent( + PasswordResetReceipt receipt, ScopeState state) { + if (receipt.accountAuthorityGeneration() != state.generation() + || receipt.accountSourceVersion() != state.sourceVersion()) { + throw new IllegalStateException( + "Latest password-reset receipt differs from Account authority"); + } + requireReceiptAuthorityIsCurrentOrEarlier(receipt, state); + } + + private void requireReceiptAuthorityIsCurrentOrEarlier( + PasswordResetReceipt receipt, ScopeState state) { + AccountAuthorityGenerationRepository.IssuanceFence currentFence = state.issuanceFence(); + requirePositiveAccountFence(currentFence, receipt.accountUuid()); + if (receipt.accountAuthorityGeneration() > state.generation() + || receipt.accountSourceVersion() > state.sourceVersion() + || receipt.issuanceFence() > currentFence.value() + || receipt.issuanceFenceSourceVersion() > currentFence.sourceVersion()) { + throw new IllegalStateException( + "Password-reset receipt is ahead of current Account authority"); + } + } + + private void requireAccountReadback(Account expected, Account readback, String passwordVerifier) { + requireAuthenticationPersistedIdentity(readback); + if (!Objects.equals(expected.getId(), readback.getId()) + || !Objects.equals(expected.getAccountUuid(), readback.getAccountUuid()) + || expected.getAccountUuidProvenance() != readback.getAccountUuidProvenance() + || !Objects.equals( + expected.getAccountUuidSourceNumericId(), readback.getAccountUuidSourceNumericId()) + || !Objects.equals(passwordVerifier, readback.getPasswordHash())) { + throw new IllegalStateException("Password-reset Account readback did not match its commit"); + } + } + + private void requireTokenAccountBinding( + net.firedevops.firemud.accountservice.entity.PasswordResetToken token, Account account) { + if (token.getId() == null + || token.getToken() == null + || token.getExpiresAt() == null + || token.getAccount() == null + || !Objects.equals(token.getAccount().getId(), account.getId())) { + throw new IllegalStateException("Password-reset token source does not match its Account row"); + } + } + + private EventEvidence passwordResetEventEvidence( + UUID accountUuid, + String requestId, + String eventId, + long sequence, + long accountAuthorityGeneration, + long sourceVersion) { + PasswordResetAuthorityEvent event = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", passwordResetStreamKey(accountUuid)), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(accountAuthorityGeneration)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(accountAuthorityGeneration), + "outboxStreamKey", passwordResetStreamKey(accountUuid), + "outboxSequence", Long.toString(sequence))))); + return new EventEvidence(event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + } + + private PasswordResetAuthorityEvent requirePasswordResetEvent( + Event event, + UUID accountUuid, + String requestId, + String eventId, + long accountAuthorityGeneration, + long sourceVersion) { + PasswordResetAuthorityEvent verified = verifyPasswordResetEvent(event, accountUuid); + if (!passwordResetStreamKey(accountUuid).equals(event.outboxStreamKey()) + || !requestId.equals(event.requestId()) + || !eventId.equals(event.eventId()) + || !Long.toString(accountAuthorityGeneration).equals(verified.accountAuthorityGeneration()) + || !Long.toString(sourceVersion).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Password-reset source event does not match its committed state"); + } + return verified; + } + + private PasswordResetAuthorityEvent verifyPasswordResetEvent(Event event, UUID accountUuid) { + if (event == null) { + throw new IllegalStateException("Password-reset source event is missing"); + } + PasswordResetAuthorityEvent verified = + PasswordResetAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + if (!MessageDigest.isEqual(event.payload(), verified.canonicalJsonUtf8()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || !event.requestId().equals(verified.requestId()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !accountUuid.toString().equals(verified.accountId()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence())) { + throw new IllegalStateException("Password-reset source event readback is inconsistent"); + } + return verified; + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { + if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Password-reset outbox checkpoint does not match its event"); + } + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, LocalDateTime tokenExpiresAt, String verifierDigest) { + if (accountUuid == null || tokenExpiresAt == null) { + throw new IllegalArgumentException("Password-reset request identity is incomplete"); + } + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, PASSWORD_RESET_REQUEST_DOMAIN); + updateLengthPrefixed(digest, PASSWORD_RESET_OPERATION_KIND); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenExpiresAt.toString()); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + if (value == null) { + throw new IllegalArgumentException("Password-reset request field is required"); + } + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + + private boolean constantTimeTextEquals(String left, String right) { + return left != null + && right != null + && MessageDigest.isEqual( + left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII)); + } + + private String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private String passwordResetRequestId(String tokenHash) { + return PASSWORD_RESET_REQUEST_ID_PREFIX + tokenHash; + } + + private String passwordResetEventId(String tokenHash) { + return PASSWORD_RESET_EVENT_ID_PREFIX + tokenHash; + } + + private String passwordResetStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; } @Override diff --git a/services/account-service/src/main/resources/db/migration/V41__account_password_reset_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V41__account_password_reset_operation_receipts.sql new file mode 100644 index 0000000000..33b0cb2992 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__account_password_reset_operation_receipts.sql @@ -0,0 +1,91 @@ +-- Immutable source receipts make a consumed Account-issued reset token an exact retry identity. +CREATE TABLE account_password_reset_operation_receipts ( + token_hash BYTEA NOT NULL, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + operation_kind VARCHAR(32) NOT NULL DEFAULT 'PASSWORD_RESET', + request_id VARCHAR(128) NOT NULL UNIQUE, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + password_verifier_digest BYTEA NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL, + account_authority_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_password_reset_operation_token_hash_check + CHECK (octet_length(token_hash) = 32), + CONSTRAINT account_password_reset_operation_identity_check + CHECK (account_id > 0 + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_kind = 'PASSWORD_RESET' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex') + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(password_verifier_digest) = 32), + CONSTRAINT account_password_reset_operation_checkpoint_check + CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND outbox_sequence > 0 + AND length(btrim(event_id)) BETWEEN 1 AND 128 + AND event_id = 'account-password-reset-event-v1:' || encode(token_hash, 'hex') + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_authority_generation > 0 + AND account_source_version > 0 + AND issuance_fence > 0 + AND issuance_fence_source_version > 0), + CONSTRAINT account_password_reset_operation_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_password_reset_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- Bind the private numeric association and canonical Account UUID at the immutable insert point. +-- [jooq ignore start] +ALTER TABLE account_password_reset_operation_receipts + ADD CONSTRAINT account_password_reset_operation_receipts_pk PRIMARY KEY (token_hash); + +CREATE FUNCTION account_password_reset_operation_account_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + persisted_uuid UUID; +BEGIN + SELECT account_uuid INTO persisted_uuid + FROM accounts + WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Password-reset receipt Account identity does not match its source row' + USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_account_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_password_reset_operation_account_binding + BEFORE INSERT ON account_password_reset_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_account_binding_guard(); + +CREATE FUNCTION account_password_reset_operation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Password-reset operation receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_password_reset_operation_immutable + BEFORE UPDATE OR DELETE ON account_password_reset_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index aca3f5a666..170eb51ed5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -7,7 +7,12 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -20,6 +25,13 @@ import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.common.security.JwtUtil; @@ -79,6 +91,9 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired private AccountRepository accountRepository; + @Autowired private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; + @Autowired private PasswordResetTokenRepository passwordResetTokenRepository; @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private EntityManagementClient entityManagementClient; @@ -186,27 +201,11 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test - void concurrentPasswordResetAttemptsConsumeTokenExactlyOnce() throws Exception { - String suffix = UUID.randomUUID().toString(); - String email = "reset-" + suffix + "@example.com"; - Long accountId = - dsl.resultQuery( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", - "reset-" + suffix, - email, - "initial-hash") - .fetchOne(0, Long.class); - assertThat(accountId).isNotNull(); - String rawToken = UUID.randomUUID().toString(); - dsl.execute( - "INSERT INTO password_reset_token (account_id, token, expires_at) VALUES (?, ?, ?)", - accountId, - rawToken, - LocalDateTime.now().plusHours(1)); - + void concurrentPasswordResetAttemptsRecoverOneExactCommit() throws Exception { + PasswordResetFixture fixture = createPasswordResetFixture("reset"); CompletePasswordResetRequest request = - new CompletePasswordResetRequest(rawToken, "new-password"); - assertExactlyOneConcurrentSuccess( + new CompletePasswordResetRequest(fixture.rawToken(), "new-password"); + assertBothConcurrentCallsSucceed( () -> { accountService.completePasswordReset(request); return null; @@ -216,36 +215,14 @@ void concurrentPasswordResetAttemptsConsumeTokenExactlyOnce() throws Exception { return null; }); - assertThat( - dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) - .fetchOne(0, Long.class)) - .isZero(); - assertThat( - dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) - .fetchOne(0, String.class)) - .isNotEqualTo("initial-hash"); + assertPasswordResetCommittedExactlyOnce(fixture); } @Test - void passwordResetConsumptionRollsBackWithAccountMutation() { - String suffix = UUID.randomUUID().toString(); - String email = "reset-rollback-" + suffix + "@example.com"; - Long accountId = - dsl.resultQuery( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", - "rr-" + suffix, - email, - "initial-hash") - .fetchOne(0, Long.class); - assertThat(accountId).isNotNull(); - String rawToken = UUID.randomUUID().toString(); - dsl.execute( - "INSERT INTO password_reset_token (account_id, token, expires_at) VALUES (?, ?, ?)", - accountId, - rawToken, - LocalDateTime.now().plusHours(1)); + void passwordResetRollbackPreservesEveryAtomicSourceComponent() { + PasswordResetFixture fixture = createPasswordResetFixture("reset-rollback"); CompletePasswordResetRequest request = - new CompletePasswordResetRequest(rawToken, "new-password"); + new CompletePasswordResetRequest(fixture.rawToken(), "new-password"); TransactionTemplate transaction = new TransactionTemplate(transactionManager); assertThatThrownBy( @@ -258,25 +235,11 @@ void passwordResetConsumptionRollsBackWithAccountMutation() { .isInstanceOf(IllegalStateException.class) .hasMessage("force rollback after token consumption"); - assertThat( - dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) - .fetchOne(0, Long.class)) - .isEqualTo(1L); - assertThat( - dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) - .fetchOne(0, String.class)) - .isEqualTo("initial-hash"); + assertPasswordResetUnchanged(fixture); accountService.completePasswordReset(request); - assertThat( - dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) - .fetchOne(0, Long.class)) - .isZero(); - assertThat( - dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) - .fetchOne(0, String.class)) - .isNotEqualTo("initial-hash"); + assertPasswordResetCommittedExactlyOnce(fixture); } @Test @@ -441,6 +404,233 @@ void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Except assertThat(response.body()).contains("\"message\":\"tenantId must be positive\""); } + private PasswordResetFixture createPasswordResetFixture(String usernamePrefix) { + return new TransactionTemplate(transactionManager) + .execute( + status -> { + String suffix = UUID.randomUUID().toString().substring(0, 20); + Account account = new Account(); + account.setUsername(usernamePrefix + "-" + suffix); + account.setEmail(usernamePrefix + "-" + suffix + "@example.com"); + account.setPasswordHash("initial-hash"); + Account saved = accountRepository.save(account); + assertThat(saved.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(saved.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + var authority = + accountAuthorityGenerationRepository.initialize( + AuthorityScope.account(saved.getAccountUuid())); + assertThat(authority.generation()).isEqualTo(1L); + assertThat(authority.sourceVersion()).isEqualTo(1L); + assertThat(authority.issuanceFence().value()).isEqualTo(1L); + assertThat(authority.issuanceFence().sourceVersion()).isEqualTo(1L); + + String rawToken = "reset-token-" + suffix; + LocalDateTime expiresAt = LocalDateTime.now().plusHours(1); + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(expiresAt); + passwordResetTokenRepository.save(token); + return new PasswordResetFixture( + saved.getId(), saved.getAccountUuid(), rawToken, "initial-hash"); + }); + } + + private void assertPasswordResetUnchanged(PasswordResetFixture fixture) { + String streamKey = passwordResetStreamKey(fixture.accountUuid()); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM password_reset_token WHERE token = ?", fixture.rawToken()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", fixture.accountId()) + .fetchOne(0, String.class)) + .isEqualTo(fixture.originalPasswordHash()); + assertThat( + dsl.resultQuery( + "SELECT generation, source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(countEvents(streamKey)).isZero(); + assertThat(countReceipts(fixture)).isZero(); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)) + .isZero(); + } + + private void assertPasswordResetCommittedExactlyOnce(PasswordResetFixture fixture) { + String streamKey = passwordResetStreamKey(fixture.accountUuid()); + String tokenHash = HexFormat.of().formatHex(sha256(fixture.rawToken())); + String expectedRequestId = "account-password-reset-request-v1:" + tokenHash; + String expectedEventId = "account-password-reset-event-v1:" + tokenHash; + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM password_reset_token WHERE token = ?", fixture.rawToken()) + .fetchOne(0, Long.class)) + .isZero(); + String passwordHash = + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", fixture.accountId()) + .fetchOne(0, String.class); + assertThat(passwordHash).startsWith("$argon2").isNotEqualTo(fixture.originalPasswordHash()); + assertThat( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat(countEvents(streamKey)).isEqualTo(1L); + assertThat(countReceipts(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT request_id FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + streamKey) + .fetchOne(0, String.class)) + .isEqualTo(expectedRequestId); + assertThat( + dsl.resultQuery( + "SELECT event_id FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + streamKey) + .fetchOne(0, String.class)) + .isEqualTo(expectedEventId); + byte[] payloadBytes = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT payload FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + streamKey) + .fetchOne(0, byte[].class), + "Password-reset source-event payload readback is missing"); + String payload = new String(payloadBytes, StandardCharsets.UTF_8); + assertThat(payload) + .doesNotContain(fixture.rawToken(), passwordHash, fixture.originalPasswordHash()); + } + + private long countEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class), + "Password-reset event count readback is missing"); + } + + private long countReceipts(PasswordResetFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_password_reset_operation_receipts " + + "WHERE token_hash = ?", + sha256(fixture.rawToken())) + .fetchOne(0, Long.class), + "Password-reset receipt count readback is missing"); + } + + private static String passwordResetStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static byte[] sha256(String value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void assertBothConcurrentCallsSucceed(Callable first, Callable second) + throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future firstResult = + executor.submit(() -> runSuccessfulWhenReleased(first, ready, start)); + Future secondResult = + executor.submit(() -> runSuccessfulWhenReleased(second, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat(firstResult.get(30, TimeUnit.SECONDS)).isNull(); + assertThat(secondResult.get(30, TimeUnit.SECONDS)).isNull(); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private static Void runSuccessfulWhenReleased( + Callable operation, CountDownLatch ready, CountDownLatch start) throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to start concurrent password reset"); + } + operation.call(); + return null; + } + + private record PasswordResetFixture( + Long accountId, UUID accountUuid, String rawToken, String originalPasswordHash) {} + private static void assertExactlyOneConcurrentSuccess(Callable first, Callable second) throws Exception { CountDownLatch ready = new CountDownLatch(2); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java new file mode 100644 index 0000000000..fb1c191e99 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -0,0 +1,535 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class PasswordResetAuthorityProducerPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "password_reset_source_proof"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String REQUEST_PREFIX = "account-password-reset-request-v1:"; + private static final String EVENT_PREFIX = "account-password-reset-event-v1:"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + + reset(fixture, seed.rawToken(), "new-password-one"); + + Account account = account(fixture, seed.accountId()); + ScopeState authority = readAuthority(fixture, seed.accountUuid()); + String streamKey = streamKey(seed.accountUuid()); + PasswordResetReceipt receipt = + transaction( + fixture.transaction(), + () -> fixture.operations().findByTokenHash(tokenHash(seed.rawToken())).orElseThrow()); + var checkpoint = + transaction( + fixture.transaction(), () -> fixture.outbox().readCheckpoint(streamKey).orElseThrow()); + var event = + transaction( + fixture.transaction(), + () -> fixture.outbox().findEvent(streamKey, receipt.outboxSequence()).orElseThrow()); + var decoded = + PasswordResetAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + String payload = new String(event.payload(), StandardCharsets.UTF_8); + + assertThat(account.getPasswordHash()).isNotEqualTo(seed.originalVerifier()); + assertThat(account.getPasswordHash()).startsWith("$argon2"); + assertThat(authority.generation()).isEqualTo(2L); + assertThat(authority.sourceVersion()).isEqualTo(2L); + assertThat(authority.issuanceFence().value()).isEqualTo(2L); + assertThat(authority.issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(tokenExists(fixture, seed.rawToken())).isFalse(); + assertThat(receipt.accountId()).isEqualTo(seed.accountId()); + assertThat(receipt.accountUuid()).isEqualTo(seed.accountUuid()); + assertThat(receipt.tokenHash()).isEqualTo(tokenHash(seed.rawToken())); + assertThat(receipt.tokenExpiresAt()).isEqualTo(seed.deadline()); + assertThat(receipt.passwordVerifierDigest()).isEqualTo(sha256Hex(account.getPasswordHash())); + assertThat(receipt.eventId()).isEqualTo(EVENT_PREFIX + tokenHash(seed.rawToken())); + assertThat(receipt.requestId()).isEqualTo(REQUEST_PREFIX + tokenHash(seed.rawToken())); + assertThat(checkpoint.outboxSequence()).isEqualTo(receipt.outboxSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(receipt.eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(receipt.eventDigest()); + assertThat(decoded.accountId()).isEqualTo(seed.accountUuid().toString()); + assertThat(decoded.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(decoded.sourceVersion()).isEqualTo("2"); + assertThat(payload) + .doesNotContain( + seed.rawToken(), + "new-password-one", + account.getPasswordHash(), + seed.originalVerifier()); + assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(1L); + assertThat(countEvents(fixture, streamKey)).isEqualTo(1L); + byte[] tokenHashBytes = HexFormat.of().parseHex(tokenHash(seed.rawToken())); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_operation_receipts " + + "SET request_digest = request_digest WHERE token_hash = ?", + tokenHashBytes)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_password_reset_operation_receipts WHERE token_hash = ?", + tokenHashBytes)) + .isInstanceOf(DataAccessException.class); + assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(1L); + } + + @Test + void exactRetryRecoversLostResponseWithoutAnySecondMutation() { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + + reset(fixture, seed.rawToken(), "recovered-password"); + StoredState committed = snapshot(fixture, seed); + reset(fixture, seed.rawToken(), "recovered-password"); + + assertThat(snapshot(fixture, seed)).isEqualTo(committed); + } + + @Test + void concurrentExactRetriesCommitOneSourceMutation() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var first = executor.submit(() -> concurrentReset(fixture, seed, ready, start)); + var second = executor.submit(() -> concurrentReset(fixture, seed, ready, start)); + assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + first.get(45, TimeUnit.SECONDS); + second.get(45, TimeUnit.SECONDS); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + StoredState state = snapshot(fixture, seed); + assertThat(state.generation()).isEqualTo(2L); + assertThat(state.sourceVersion()).isEqualTo(2L); + assertThat(state.issuanceFence()).isEqualTo(2L); + assertThat(state.tokenCount()).isZero(); + assertThat(state.receiptCount()).isEqualTo(1L); + assertThat(state.eventCount()).isEqualTo(1L); + } + + @Test + void changedRetryConflictsAndConsecutiveResetsRequireExactPriorSourceProof() { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + reset(fixture, seed.rawToken(), "first-password"); + StoredState committed = snapshot(fixture, seed); + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "different-password")) + .isInstanceOf(OperationConflictException.class); + assertThat(snapshot(fixture, seed)).isEqualTo(committed); + + String secondToken = "second-token-" + UUID.randomUUID(); + LocalDateTime secondDeadline = LocalDateTime.now().plusHours(2); + transaction( + fixture.transaction(), + () -> { + Account owner = fixture.accounts().findById(seed.accountId()).orElseThrow(); + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(owner); + token.setToken(secondToken); + token.setExpiresAt(secondDeadline); + fixture.tokens().save(token); + return null; + }); + reset(fixture, secondToken, "second-password"); + + ScopeState authority = readAuthority(fixture, seed.accountUuid()); + assertThat(authority.generation()).isEqualTo(3L); + assertThat(authority.sourceVersion()).isEqualTo(3L); + assertThat(authority.issuanceFence().value()).isEqualTo(3L); + assertThat(countEvents(fixture, streamKey(seed.accountUuid()))).isEqualTo(2L); + assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(2L); + } + + @Test + void appendAndReceiptReadbackFailuresRollBackEveryEarlierMutation() { + Fixture appendFailure = newFixture(); + Seed appendSeed = seedAccountAndToken(appendFailure, "initial-password"); + appendFailure + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "ADD CONSTRAINT reject_password_reset_producer_event " + + "CHECK (event_id NOT LIKE 'account-password-reset-event-v1:%')"); + + assertThatThrownBy(() -> reset(appendFailure, appendSeed.rawToken(), "append-failure-password")) + .isInstanceOf(RuntimeException.class); + assertUnchangedAfterRollback(appendFailure, appendSeed); + + Fixture readbackFailure = newFixture(); + Seed readbackSeed = seedAccountAndToken(readbackFailure, "initial-password"); + AccountPasswordResetOperationRepository hideInsertedReceipt = + new AccountPasswordResetOperationRepository(readbackFailure.transactionDsl()) { + private final AtomicInteger lookups = new AtomicInteger(); + + @Override + public Optional findByTokenHash(String tokenHash) { + int lookup = lookups.incrementAndGet(); + if (lookup >= 3) { + return Optional.empty(); + } + return super.findByTokenHash(tokenHash); + } + }; + AccountServiceImpl service = newService(readbackFailure, hideInsertedReceipt); + + assertThatThrownBy( + () -> + transaction( + readbackFailure.transaction(), + () -> { + service.completePasswordReset( + new CompletePasswordResetRequest( + readbackSeed.rawToken(), "readback-failure-password")); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt readback is missing"); + assertUnchangedAfterRollback(readbackFailure, readbackSeed); + } + + @Test + void issuanceFenceOverflowRollsBackTokenPasswordAuthorityAndOutbox() { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_issuance_fences DISABLE TRIGGER account_authority_issuance_fences_monotonic"); + try { + fixture + .setupDsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = ?, source_version = ? WHERE account_uuid = ?", + Long.MAX_VALUE, + 11L, + seed.accountUuid()); + } finally { + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_issuance_fences ENABLE TRIGGER account_authority_issuance_fences_monotonic"); + } + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "overflow-password")) + .isInstanceOf(RuntimeException.class); + assertUnchangedAfterRollback(fixture, seed); + assertThat(readAuthority(fixture, seed.accountUuid()).issuanceFence().value()) + .isEqualTo(Long.MAX_VALUE); + } + + private boolean concurrentReset( + Fixture fixture, Seed seed, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + reset(fixture, seed.rawToken(), "concurrent-password"); + return true; + } + + private Fixture newFixture() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountRepository accounts = new AccountRepository(transactionDsl); + AccountAuthorityGenerationRepository authority = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountPasswordResetOperationRepository operations = + new AccountPasswordResetOperationRepository(transactionDsl); + PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); + return new Fixture( + setupDsl, + transactionDsl, + transactionManager, + transaction, + accounts, + authority, + outbox, + operations, + tokens); + } + + private Seed seedAccountAndToken(Fixture fixture, String initialVerifier) { + return transaction( + fixture.transaction(), + () -> { + Account account = new Account(); + String unique = UUID.randomUUID().toString(); + account.setUsername("reset-" + unique); + account.setEmail("reset-" + unique + "@example.test"); + account.setPasswordHash(initialVerifier); + Account saved = fixture.accounts().save(account); + fixture.authority().initialize(AuthorityScope.account(saved.getAccountUuid())); + + String tokenValue = "reset-token-" + unique; + LocalDateTime deadline = LocalDateTime.now().plusHours(2); + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(saved); + token.setToken(tokenValue); + token.setExpiresAt(deadline); + fixture.tokens().save(token); + LocalDateTime storedDeadline = + fixture.tokens().findByToken(tokenValue).orElseThrow().getExpiresAt(); + return new Seed( + saved.getId(), saved.getAccountUuid(), tokenValue, storedDeadline, initialVerifier); + }); + } + + private AccountServiceImpl newService( + Fixture fixture, AccountPasswordResetOperationRepository operations) { + return new AccountServiceImpl( + fixture.accounts(), + fixture.authority(), + fixture.outbox(), + operations, + null, // audit outbox + null, // connect scopes + null, // join operations + null, // membership transition receipts + null, // membership authority producer + null, // email login challenges + null, // realm grants + null, // tenant memberships + null, // membership role snapshots + null, // account mapper is not on the password-reset path + null, // profiles + null, // profile mapper + null, // payment transactions + null, // subscriptions + null, // external account identities + fixture.tokens(), + null, // email verification tokens + null, // notifications + null, // email delivery + null, // mail properties + null, // token properties + null, // JWT auth properties + null, // game session client + null, // entity management client + null, // JWT utility + null, // session service + fixture.transactionManager()); + } + + private void reset(Fixture fixture, String rawToken, String password) { + AccountServiceImpl service = newService(fixture, fixture.operations()); + transaction( + fixture.transaction(), + () -> { + service.completePasswordReset(new CompletePasswordResetRequest(rawToken, password)); + return null; + }); + } + + private void assertUnchangedAfterRollback(Fixture fixture, Seed seed) { + Account account = account(fixture, seed.accountId()); + ScopeState authority = readAuthority(fixture, seed.accountUuid()); + assertThat(account.getPasswordHash()).isEqualTo(seed.originalVerifier()); + assertThat(tokenExists(fixture, seed.rawToken())).isTrue(); + assertThat(authority.generation()).isEqualTo(1L); + assertThat(authority.sourceVersion()).isEqualTo(1L); + assertThat(countReceipts(fixture, seed.accountId())).isZero(); + assertThat(countEvents(fixture, streamKey(seed.accountUuid()))).isZero(); + assertThat(countRows(fixture.setupDsl(), "account_authority_outbox_streams")).isZero(); + } + + private StoredState snapshot(Fixture fixture, Seed seed) { + Account account = account(fixture, seed.accountId()); + ScopeState authority = readAuthority(fixture, seed.accountUuid()); + return new StoredState( + account.getPasswordHash(), + authority.generation(), + authority.sourceVersion(), + authority.issuanceFence().value(), + tokenExists(fixture, seed.rawToken()) ? 1L : 0L, + countReceipts(fixture, seed.accountId()), + countEvents(fixture, streamKey(seed.accountUuid()))); + } + + private Account account(Fixture fixture, long accountId) { + return transaction( + fixture.transaction(), () -> fixture.accounts().findById(accountId).orElseThrow()); + } + + private ScopeState readAuthority(Fixture fixture, UUID accountUuid) { + return transaction( + fixture.transaction(), () -> fixture.authority().read(AuthorityScope.account(accountUuid))); + } + + private boolean tokenExists(Fixture fixture, String rawToken) { + return transaction( + fixture.transaction(), () -> fixture.tokens().findByToken(rawToken).isPresent()); + } + + private long countReceipts(Fixture fixture, long accountId) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_password_reset_operation_receipts WHERE account_id = ?", + accountId) + .fetchOne(0, Long.class), + "Password-reset receipt count readback is missing"); + } + + private long countEvents(Fixture fixture, String streamKey) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class), + "Password-reset event count readback is missing"); + } + + private long countRows(DSLContext dsl, String table) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "Password-reset row count readback is missing"); + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String tokenHash(String rawToken) { + return sha256Hex(rawToken); + } + + private String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent password-reset barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent password-reset proof was interrupted", interrupted); + } + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + DSLContext setupDsl, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transaction, + AccountRepository accounts, + AccountAuthorityGenerationRepository authority, + AccountAuthorityOutboxRepository outbox, + AccountPasswordResetOperationRepository operations, + PasswordResetTokenRepository tokens) {} + + private record Seed( + long accountId, + UUID accountUuid, + String rawToken, + LocalDateTime deadline, + String originalVerifier) {} + + private record StoredState( + String passwordVerifier, + long generation, + long sourceVersion, + long issuanceFence, + long tokenCount, + long receiptCount, + long eventCount) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java new file mode 100644 index 0000000000..d3425b1e45 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.LocalDateTime; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountPasswordResetOperationRepositoryTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c6ca3e35-9ba4-46a4-967b-f83ddb0d693e"); + private final DSLContext dsl = mock(DSLContext.class); + private final AccountPasswordResetOperationRepository repository = + new AccountPasswordResetOperationRepository(dsl); + + @Test + void lookupsAndInsertionRequireAnOwnerTransaction() throws ReflectiveOperationException { + assertMandatory( + AccountPasswordResetOperationRepository.class.getMethod("findByTokenHash", String.class)); + assertMandatory( + AccountPasswordResetOperationRepository.class.getMethod("findByRequestId", String.class)); + assertMandatory( + AccountPasswordResetOperationRepository.class.getMethod( + "insert", AccountPasswordResetOperationRepository.PasswordResetReceipt.class)); + + assertThatThrownBy(() -> repository.findByTokenHash("0".repeat(64))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account transaction"); + verifyNoInteractions(dsl); + } + + @Test + void receiptEvidenceRejectsMalformedOrNonAccountBindingsBeforeStorageAccess() { + assertThatThrownBy(() -> receipt("not-a-hash", "0".repeat(64), "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> receipt("0".repeat(64), "bad-digest", "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> receipt("0".repeat(64), "0".repeat(64), "bad-verifier")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountPasswordResetOperationRepository.PasswordResetReceipt( + 9L, + ACCOUNT_UUID, + "0".repeat(64), + "PASSWORD_RESET", + "wrong-request-id", + 1, + "1".repeat(64), + LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789), + "2".repeat(64), + streamKey(), + 1L, + "account-password-reset-event-v1:" + "0".repeat(64), + "sha256:" + "3".repeat(64), + 2L, + 2L, + 3L, + 3L)) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void committedReceiptRetainsExactLocalDeadlineAndAccountFenceEvidence() { + ScopeState authority = + new ScopeState( + AuthorityScope.account(ACCOUNT_UUID), 2L, 2L, new IssuanceFence(ACCOUNT_UUID, 4L, 3L)); + LocalDateTime localDeadline = LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789); + var receipt = + AccountPasswordResetOperationRepository.PasswordResetReceipt.committed( + 9L, + ACCOUNT_UUID, + "0".repeat(64), + "account-password-reset-request-v1:" + "0".repeat(64), + "1".repeat(64), + localDeadline, + "2".repeat(64), + streamKey(), + 7L, + "account-password-reset-event-v1:" + "0".repeat(64), + "sha256:" + "3".repeat(64), + authority, + authority.issuanceFence()); + + assertThat(receipt.tokenExpiresAt()).isEqualTo(localDeadline); + assertThat(receipt.issuanceFenceEvidence()).isEqualTo(new IssuanceFence(ACCOUNT_UUID, 4L, 3L)); + assertThat(receipt.outboxSequence()).isEqualTo(7L); + verifyNoInteractions(dsl); + } + + private static AccountPasswordResetOperationRepository.PasswordResetReceipt receipt( + String tokenHash, String requestDigest, String verifierDigest) { + return new AccountPasswordResetOperationRepository.PasswordResetReceipt( + 9L, + ACCOUNT_UUID, + tokenHash, + "PASSWORD_RESET", + "account-password-reset-request-v1:" + tokenHash, + 1, + requestDigest, + LocalDateTime.of(2030, 1, 2, 3, 4, 5), + verifierDigest, + streamKey(), + 1L, + "account-password-reset-event-v1:" + tokenHash, + "sha256:" + "3".repeat(64), + 2L, + 2L, + 3L, + 3L); + } + + private static String streamKey() { + return "account:auth-authority:v1:account/" + ACCOUNT_UUID; + } + + private void assertMandatory(java.lang.reflect.Method method) { + Transactional annotation = method.getAnnotation(Transactional.class); + assertThat(annotation).isNotNull(); + assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY); + } +} 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 f479a1aa49..4c275bef6d 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 @@ -11,11 +11,19 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; import java.util.Collection; +import java.util.HexFormat; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -50,11 +58,20 @@ import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -72,6 +89,8 @@ import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; @@ -94,6 +113,8 @@ class AccountServiceImplTest { private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; @Mock private AccountRepository accountRepository; @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; + @Mock private AccountAuthorityOutboxRepository accountAuthorityOutboxRepository; + @Mock private AccountPasswordResetOperationRepository passwordResetOperationRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @@ -238,6 +259,8 @@ void setup() { new AccountServiceImpl( accountRepository, accountAuthorityGenerationRepository, + accountAuthorityOutboxRepository, + passwordResetOperationRepository, accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, @@ -2283,6 +2306,8 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { new AccountServiceImpl( accountRepository, accountAuthorityGenerationRepository, + accountAuthorityOutboxRepository, + passwordResetOperationRepository, accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, @@ -5392,76 +5417,209 @@ void requestPasswordResetUnknownEmailIsNeutral() { } @Test - void completePasswordResetConsumesTokenBeforeUpdatingPassword() { - Account account = new Account(); - account.setId(1L); - account.setPasswordHash("old-hash"); - net.firedevops.firemud.accountservice.entity.PasswordResetToken token = - new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); - token.setId(7L); - token.setAccount(account); - token.setToken("tok"); - token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); - when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); - when(passwordResetTokenRepository.consumeIfUnexpired( - org.mockito.ArgumentMatchers.eq(token), - org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) - .thenReturn(true); + void completePasswordResetCommitsTokenPasswordAuthorityEventAndReceiptInOrder() { + PasswordResetHarness harness = + preparePasswordResetCommit( + "reset-token-order", LocalDateTime.now().plusHours(1), null, true); service.completePasswordReset( new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( - "tok", "new-password")); + "reset-token-order", "new-password")); + + PasswordResetReceipt receipt = harness.receipt().get(); + assertNotNull(receipt); + assertFalse("old-verifier".equals(harness.account().getPasswordHash())); + assertEquals(2L, receipt.accountAuthorityGeneration()); + assertEquals(2L, receipt.accountSourceVersion()); + assertEquals(8L, receipt.issuanceFence()); + assertEquals(6L, receipt.issuanceFenceSourceVersion()); + assertEquals(sha256Hex(harness.account().getPasswordHash()), receipt.passwordVerifierDigest()); + assertEquals(passwordResetTokenHash("reset-token-order"), receipt.tokenHash()); + assertFalse( + new String(harness.event().get().payload(), StandardCharsets.UTF_8) + .contains("reset-token-order")); - assertFalse("old-hash".equals(account.getPasswordHash())); org.mockito.InOrder order = - org.mockito.Mockito.inOrder(passwordResetTokenRepository, accountRepository); + org.mockito.Mockito.inOrder( + passwordResetOperationRepository, + passwordResetTokenRepository, + accountRepository, + accountAuthorityGenerationRepository, + accountAuthorityOutboxRepository); + order.verify(passwordResetOperationRepository).findByTokenHash(receipt.tokenHash()); + order.verify(passwordResetTokenRepository).findByToken("reset-token-order"); + order.verify(accountRepository).findByIdForUpdate(harness.account().getId()); + order.verify(passwordResetOperationRepository).findByTokenHash(receipt.tokenHash()); + order.verify(passwordResetTokenRepository).findByToken("reset-token-order"); + order.verify(accountAuthorityGenerationRepository).read(harness.scope()); + order.verify(accountAuthorityOutboxRepository).readCheckpoint(receipt.outboxStreamKey()); order .verify(passwordResetTokenRepository) .consumeIfUnexpired( - org.mockito.ArgumentMatchers.eq(token), - org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); - order.verify(accountRepository).save(account); + org.mockito.ArgumentMatchers.eq(harness.token()), + org.mockito.ArgumentMatchers.any(LocalDateTime.class)); + order + .verify(accountRepository) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.eq(harness.account()), + org.mockito.ArgumentMatchers.anyString()); + order + .verify(accountAuthorityGenerationRepository) + .advance(harness.initialAuthority(), harness.initialAuthority().issuanceFence()); + order + .verify(accountAuthorityOutboxRepository) + .append( + org.mockito.ArgumentMatchers.eq(receipt.outboxStreamKey()), + org.mockito.ArgumentMatchers.eq(receipt.requestId()), + org.mockito.ArgumentMatchers.any()); + order.verify(passwordResetOperationRepository).insert(receipt); + } + + @Test + void completePasswordResetRejectsMissingOrContradictorySourceBeforeMutation() { + ScopeState progressedWithoutHistory = + new ScopeState( + AuthorityScope.account(UUID.fromString("5d79f453-4f04-4cad-8561-cce2a2ab57bc")), + 2L, + 2L, + new IssuanceFence(UUID.fromString("5d79f453-4f04-4cad-8561-cce2a2ab57bc"), 7L, 4L)); + preparePasswordResetCommit( + "reset-token-unproven", LocalDateTime.now().plusHours(1), progressedWithoutHistory, true); + + assertThrows( + IllegalStateException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "reset-token-unproven", "new-password"))); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) - .delete(token); + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountAuthorityGenerationRepository, org.mockito.Mockito.never()) + .advance(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuthorityOutboxRepository, org.mockito.Mockito.never()) + .append( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(passwordResetOperationRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + + @Test + void completePasswordResetRejectsAStreamEventAtThePristineSourceBaseline() { + PasswordResetHarness harness = + preparePasswordResetCommit( + "reset-token-contradictory-baseline", LocalDateTime.now().plusHours(1), null, true); + harness + .event() + .set( + new Event( + "account:auth-authority:v1:account/" + harness.scope().accountId(), + "unowned-prior-request", + 1L, + "unowned-prior-event", + "sha256:" + "4".repeat(64), + new byte[] {1})); + + assertThrows( + IllegalStateException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "reset-token-contradictory-baseline", "new-password"))); + + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountAuthorityGenerationRepository, org.mockito.Mockito.never()) + .advance(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuthorityOutboxRepository, org.mockito.Mockito.never()) + .append( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(passwordResetOperationRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); } @Test - void completePasswordResetRejectsAlreadyConsumedTokenBeforePasswordMutation() { - Account account = new Account(); - account.setPasswordHash("old-hash"); - net.firedevops.firemud.accountservice.entity.PasswordResetToken token = - new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); - token.setId(7L); - token.setAccount(account); - token.setToken("tok"); - token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); - when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); - when(passwordResetTokenRepository.consumeIfUnexpired( - org.mockito.ArgumentMatchers.eq(token), - org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) - .thenReturn(false); + void completePasswordResetRejectsMissingUuidProvenanceBeforeAuthorityReads() { + PasswordResetHarness harness = + preparePasswordResetCommit( + "reset-token-unproven-identity", LocalDateTime.now().plusHours(1), null, true); + harness.account().setAccountUuidProvenance(null); assertThrows( - IllegalArgumentException.class, + IllegalStateException.class, () -> service.completePasswordReset( new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( - "tok", "new-password"))); + "reset-token-unproven-identity", "new-password"))); - assertEquals("old-hash", account.getPasswordHash()); - org.mockito.Mockito.verifyNoInteractions(accountRepository); + verifyNoInteractions(accountAuthorityGenerationRepository, accountAuthorityOutboxRepository); org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) - .delete(token); + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); } @Test - void completePasswordResetRejectsExpiredTokenBeforeConsumption() { - net.firedevops.firemud.accountservice.entity.PasswordResetToken token = - new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); - token.setId(7L); - token.setToken("tok"); - token.setExpiresAt(java.time.LocalDateTime.now().minusSeconds(1)); - when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + void completePasswordResetExactRetryRecoversLostResponseWithoutMutation() { + PasswordResetRetryHarness harness = + preparePasswordResetRetry("reset-token-exact", "password-one"); + + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "reset-token-exact", "password-one")); + + verifyNoInteractions(passwordResetTokenRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountAuthorityGenerationRepository, org.mockito.Mockito.never()) + .advance(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuthorityOutboxRepository, org.mockito.Mockito.never()) + .append( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(passwordResetOperationRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + assertEquals(harness.receipt(), harness.receiptReadback().get()); + } + + @Test + void completePasswordResetChangedRetryConflictsWhileVerifierIsUnchanged() { + preparePasswordResetRetry("reset-token-changed", "password-one"); + + assertThrows( + OperationConflictException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "reset-token-changed", "different-password"))); + + verifyNoInteractions(passwordResetTokenRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountAuthorityGenerationRepository, org.mockito.Mockito.never()) + .advance(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(passwordResetOperationRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + + @Test + void completePasswordResetExpiredReceiptCannotRecoverLostResponse() { + preparePasswordResetRetry( + "reset-token-expired-receipt", "password-one", LocalDateTime.now().minusSeconds(1), false); IllegalArgumentException exception = assertThrows( @@ -5469,16 +5627,339 @@ void completePasswordResetRejectsExpiredTokenBeforeConsumption() { () -> service.completePasswordReset( new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( - "tok", "new-password"))); + "reset-token-expired-receipt", "password-one"))); assertEquals("Token expired", exception.getMessage()); - org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) - .consumeIfUnexpired( - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); - org.mockito.Mockito.verifyNoInteractions(accountRepository); + verifyNoInteractions(passwordResetTokenRepository, accountAuthorityGenerationRepository); + org.mockito.Mockito.verify(accountAuthorityOutboxRepository, org.mockito.Mockito.never()) + .findEvent( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); } + @Test + void completePasswordResetSupersededVerifierIsNotReportedAsCallerConflict() { + PasswordResetRetryHarness harness = + preparePasswordResetRetry("reset-token-superseded", "password-one"); + harness.account().setPasswordHash(hash("later-password")); + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "reset-token-superseded", "password-one"))); + + assertEquals("Password-reset result was superseded", exception.getMessage()); + verifyNoInteractions(passwordResetTokenRepository, accountAuthorityGenerationRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void completePasswordResetFailsClosedWhenImmutableEventReadbackDiffers() { + PasswordResetHarness harness = + preparePasswordResetCommit( + "reset-token-event-readback", LocalDateTime.now().plusHours(1), null, true); + harness.corruptEventReadback().set(true); + + assertThrows( + IllegalStateException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "reset-token-event-readback", "new-password"))); + + org.mockito.Mockito.verify(passwordResetOperationRepository) + .insert(org.mockito.ArgumentMatchers.any()); + assertNotNull(harness.receipt().get()); + } + + private PasswordResetHarness preparePasswordResetCommit( + String rawToken, + LocalDateTime tokenExpiresAt, + ScopeState requestedInitialAuthority, + boolean receiptReadbackEnabled) { + long accountId = 101L; + UUID accountUuid = + requestedInitialAuthority == null + ? UUID.fromString("723d61a5-8e11-4b8f-9e01-3ab48e9b2702") + : requestedInitialAuthority.scope().accountId(); + AuthorityScope scope = AuthorityScope.account(accountUuid); + ScopeState initialAuthority = + requestedInitialAuthority == null + ? new ScopeState(scope, 1L, 1L, new IssuanceFence(accountUuid, 7L, 5L)) + : requestedInitialAuthority; + + Account account = new Account(); + account.setId(accountId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(accountId); + account.setPasswordHash("old-verifier"); + + Account tokenAccount = new Account(); + tokenAccount.setId(accountId); + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(73L); + token.setAccount(tokenAccount); + token.setToken(rawToken); + token.setExpiresAt(tokenExpiresAt); + + String tokenHash = passwordResetTokenHash(rawToken); + String requestId = "account-password-reset-request-v1:" + tokenHash; + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + AtomicReference receipt = new AtomicReference<>(); + AtomicReference event = new AtomicReference<>(); + AtomicBoolean corruptEventReadback = new AtomicBoolean(false); + AtomicReference authority = new AtomicReference<>(initialAuthority); + AtomicReference tokenLookupCount = new AtomicReference<>(0); + + when(passwordResetOperationRepository.findByTokenHash(tokenHash)) + .thenAnswer( + ignored -> + receiptReadbackEnabled ? Optional.ofNullable(receipt.get()) : Optional.empty()); + when(passwordResetOperationRepository.findByRequestId(org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.empty()); + when(passwordResetOperationRepository.insert(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + PasswordResetReceipt inserted = invocation.getArgument(0); + receipt.set(inserted); + return inserted; + }); + when(passwordResetTokenRepository.findByToken(rawToken)) + .thenAnswer( + ignored -> { + int lookupNumber = tokenLookupCount.get() + 1; + tokenLookupCount.set(lookupNumber); + return lookupNumber <= 2 ? Optional.of(token) : Optional.empty(); + }); + when(passwordResetTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(LocalDateTime.class))) + .thenReturn(true); + when(accountRepository.findByIdForUpdate(accountId)).thenReturn(Optional.of(account)); + when(accountRepository.updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.eq(account), org.mockito.ArgumentMatchers.anyString())) + .thenAnswer( + invocation -> { + account.setPasswordHash(invocation.getArgument(1)); + return account; + }); + when(accountAuthorityGenerationRepository.read(scope)).thenAnswer(ignored -> authority.get()); + when(accountAuthorityGenerationRepository.advance( + org.mockito.ArgumentMatchers.any(ScopeState.class), + org.mockito.ArgumentMatchers.any(IssuanceFence.class))) + .thenAnswer( + invocation -> { + ScopeState previous = invocation.getArgument(0); + IssuanceFence previousFence = previous.issuanceFence(); + ScopeState next = + new ScopeState( + previous.scope(), + previous.generation() + 1L, + previous.sourceVersion() + 1L, + new IssuanceFence( + previousFence.accountId(), + previousFence.value() + 1L, + previousFence.sourceVersion() + 1L)); + authority.set(next); + return next; + }); + when(accountAuthorityOutboxRepository.readCheckpoint(streamKey)) + .thenAnswer( + ignored -> { + Event stored = event.get(); + return stored == null + ? Optional.empty() + : Optional.of( + new Checkpoint( + stored.outboxStreamKey(), + stored.outboxSequence(), + stored.eventId(), + stored.eventDigest())); + }); + when(accountAuthorityOutboxRepository.append( + org.mockito.ArgumentMatchers.eq(streamKey), + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + @SuppressWarnings("unchecked") + LongFunction factory = invocation.getArgument(2); + EventEvidence evidence = factory.apply(1L); + Event appended = + new Event( + streamKey, + requestId, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + event.set(appended); + return appended; + }); + when(accountAuthorityOutboxRepository.findEvent( + org.mockito.ArgumentMatchers.eq(streamKey), org.mockito.ArgumentMatchers.anyLong())) + .thenAnswer( + invocation -> { + Event stored = event.get(); + if (stored == null || stored.outboxSequence() != invocation.getArgument(1)) { + return Optional.empty(); + } + if (corruptEventReadback.get()) { + return Optional.of( + new Event( + stored.outboxStreamKey(), + stored.requestId(), + stored.outboxSequence(), + stored.eventId(), + "sha256:" + "0".repeat(64), + stored.payload())); + } + return Optional.of(stored); + }); + + return new PasswordResetHarness( + account, token, tokenHash, scope, initialAuthority, receipt, event, corruptEventReadback); + } + + private PasswordResetRetryHarness preparePasswordResetRetry(String rawToken, String password) { + return preparePasswordResetRetry(rawToken, password, LocalDateTime.now().plusHours(1), true); + } + + private PasswordResetRetryHarness preparePasswordResetRetry( + String rawToken, + String password, + LocalDateTime tokenExpiresAt, + boolean currentVerifierMatchesReceipt) { + long accountId = 107L; + UUID accountUuid = UUID.fromString("8950829f-970b-4712-8d67-fbfe1c8813f5"); + AuthorityScope scope = AuthorityScope.account(accountUuid); + Account account = new Account(); + account.setId(accountId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(accountId); + String passwordVerifier = hash(password); + account.setPasswordHash( + currentVerifierMatchesReceipt ? passwordVerifier : hash("superseding-password")); + + String tokenHash = passwordResetTokenHash(rawToken); + String requestId = "account-password-reset-request-v1:" + tokenHash; + String eventId = "account-password-reset-event-v1:" + tokenHash; + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String verifierDigest = sha256Hex(passwordVerifier); + String requestDigest = + resetRequestDigest(accountUuid, tokenHash, tokenExpiresAt, verifierDigest); + ScopeState committedAuthority = + new ScopeState(scope, 2L, 2L, new IssuanceFence(accountUuid, 8L, 6L)); + PasswordResetAuthorityEvent eventEvidence = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "2", + "outboxStreamKey", streamKey, + "outboxSequence", "1")))); + Event event = + new Event( + streamKey, + requestId, + 1L, + eventEvidence.eventId(), + eventEvidence.eventDigest(), + eventEvidence.canonicalJsonUtf8()); + PasswordResetReceipt receipt = + PasswordResetReceipt.committed( + accountId, + accountUuid, + tokenHash, + requestId, + requestDigest, + tokenExpiresAt, + verifierDigest, + streamKey, + 1L, + eventId, + eventEvidence.eventDigest(), + committedAuthority, + committedAuthority.issuanceFence()); + AtomicReference receiptReadback = new AtomicReference<>(receipt); + + when(passwordResetOperationRepository.findByTokenHash(tokenHash)) + .thenAnswer(ignored -> Optional.ofNullable(receiptReadback.get())); + when(accountRepository.findByIdForUpdate(accountId)).thenReturn(Optional.of(account)); + when(accountAuthorityGenerationRepository.read(scope)).thenReturn(committedAuthority); + when(accountAuthorityOutboxRepository.findEvent(streamKey, 1L)).thenReturn(Optional.of(event)); + return new PasswordResetRetryHarness(account, receipt, receiptReadback); + } + + private static String passwordResetTokenHash(String rawToken) { + return sha256Hex(rawToken); + } + + private static String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private static String resetRequestDigest( + UUID accountUuid, String tokenHash, LocalDateTime tokenExpiresAt, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + resetFrame(digest, "account-password-reset-request/v1"); + resetFrame(digest, "PASSWORD_RESET"); + resetFrame(digest, accountUuid.toString()); + resetFrame(digest, tokenHash); + resetFrame(digest, tokenExpiresAt.toString()); + resetFrame(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private static void resetFrame(MessageDigest digest, String value) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + + private record PasswordResetHarness( + Account account, + net.firedevops.firemud.accountservice.entity.PasswordResetToken token, + String tokenHash, + AuthorityScope scope, + ScopeState initialAuthority, + AtomicReference receipt, + AtomicReference event, + AtomicBoolean corruptEventReadback) {} + + private record PasswordResetRetryHarness( + Account account, + PasswordResetReceipt receipt, + AtomicReference receiptReadback) {} + @Test void requestPasswordResetContainsDeliveryFailureAfterSavingToken() { Account account = new Account(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java new file mode 100644 index 0000000000..f2068dcc0f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java @@ -0,0 +1,372 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account password-reset authority events. */ +public final class PasswordResetAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-password-reset-event/v1"; + public static final String EVENT_TYPE = "PASSWORD_RESET_COMMITTED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff"); + private static final Set WIRE_FIELDS; + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private PasswordResetAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static PasswordResetAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static PasswordResetAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static PasswordResetAuthorityEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static PasswordResetAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + requireNonEmptyText(event, "eventId", "event"); + requireNonEmptyText(event, "requestId", "event"); + + String accountId = requireUuid(event, "accountId", "event"); + String sourceScope = "account/" + accountId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event"); + String accountAuthorityGeneration = + requirePositiveDecimal(event, "accountAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + + JsonNode cutoffNode = event.get("accountSecurityCutoff"); + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff"); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + if (!accountAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!streamKey.equals(cutoffStream)) { + throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!outboxSequence.equals(cutoffSequence)) { + throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + private static PasswordResetAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + return new PasswordResetAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("accountId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("accountAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + new AccountSecurityCutoff( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireNonEmptyText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isEmpty()) { + throw invalid(path + "." + field, "must be nonempty"); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed event evidence. */ + public static final class PasswordResetAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String accountId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final String eventDigest; + private final String canonicalJson; + + private PasswordResetAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String accountId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json new file mode 100644 index 0000000000..0c2a591b0b --- /dev/null +++ b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json @@ -0,0 +1,136 @@ +{ + "schemaVersion": "account-auth-password-reset-event-vectors/v1", + "validEvents": [ + { + "name": "standard-password-reset-cutoff", + "expectedEventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"7\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"7\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07\",\"eventId\":\"password-reset-event-001\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-001\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"12\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-001", + "requestId": "password-reset-request-001", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3", + "accountAuthorityGeneration": "7", + "sourceVersion": "12", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3" + }, + "eventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65\",\"eventId\":\"password-reset-event-large-counters\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-large-counters\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-large-counters", + "requestId": "password-reset-request-large-counters", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65" + } + } + ], + "changedDeclaredFieldMutations": [ + {"name": "event-id", "changes": {"eventId": "password-reset-event-002"}}, + {"name": "request-id", "changes": {"requestId": "password-reset-request-002"}}, + { + "name": "account-identity-and-derived-scope", + "changes": { + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "outboxSequence": "3" + } + } + }, + { + "name": "outbox-sequence-and-cutoff", + "changes": { + "outboxSequence": "4", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "4" + } + } + }, + { + "name": "account-authority-generation-and-cutoff", + "changes": { + "accountAuthorityGeneration": "8", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "8", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3" + } + } + }, + {"name": "source-version", "changes": {"sourceVersion": "13"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "requestId", + "outboxSequence", + "outboxStreamKey", + "eventType", + "eventId", + "eventDigest", + "accountId", + "accountAuthorityGeneration", + "accountSecurityCutoff", + "schemaVersion", + "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v2"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_REQUESTED"}, + {"name": "missing-required-event-id", "op": "remove", "path": "/eventId"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "missing-required-request-id", "op": "remove", "path": "/requestId"}, + {"name": "null-account-id", "op": "replace", "path": "/accountId", "value": null}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "018F8F0A-1A6B-7B13-8D04-5F6E7D8C9B0A"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 3}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "03"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-3"}, + {"name": "exponent-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "3e0"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 7}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "8"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "4"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-credential-material", "op": "add", "path": "/passwordVerifier", "value": "secret"}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..55a7fdf293 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class PasswordResetAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + PasswordResetAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-password-reset-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + PasswordResetAuthorityEvent verified = + PasswordResetAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + PasswordResetAuthorityEvent sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + PasswordResetAuthorityEvent large = + PasswordResetAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changingAnyDeclaredSourceEvidenceCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + PasswordResetAuthorityEvent sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedCanonicalEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + PasswordResetAuthorityEvent verified = + PasswordResetAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAreRejectedBeforeShapeValidation() { + assertThatThrownBy( + () -> + PasswordResetAuthorityEventV1Codec.verify( + "{\"eventId\":\"first\",\"eventId\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceIsImmutableAndCanonicalBytesAreCallerOwned() { + JsonNode vector = vectors.path("validEvents").get(0); + PasswordResetAuthorityEvent event = + PasswordResetAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(event.accountSecurityCutoff().accountAuthorityGeneration()) + .isEqualTo(event.accountAuthorityGeneration()); + assertThat(event.accountSecurityCutoff().outboxStreamKey()).isEqualTo(event.outboxStreamKey()); + assertThat(event.accountSecurityCutoff().outboxSequence()).isEqualTo(event.outboxSequence()); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} From 63a3ec1b861e292f93b36bc8db9f3838fa8878dc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:28:37 +1300 Subject: [PATCH 02/22] Resolve retained Game Session tenants to verified UUIDs for Account admission --- .../game-session-service/runtime-and-data.md | 2 + .../gamesession/client/AccountClient.java | 6 +- .../command/text/PlayCommandHandler.java | 88 ++++-- ...untimeTenantUuidResolverConfiguration.java | 31 ++ ...onRetainedTenantAssociationRepository.java | 56 ++++ .../RetainedRuntimeTenantUuidResolver.java | 73 +++++ ...tAssociationRepositoryIntegrationTest.java | 105 +++++++ .../gamesession/client/AccountClientTest.java | 112 ++++++- .../command/text/LoginCommandHandlerTest.java | 8 + .../command/text/PlayCommandHandlerTest.java | 279 ++++++++++++++++-- .../text/SessionResumptionFlowTest.java | 40 +-- .../text/TextCommandInterpreterTest.java | 22 +- ...RetainedRuntimeTenantUuidResolverTest.java | 104 +++++++ .../RuntimeMembershipTestFixtures.java | 94 +++++- 14 files changed, 951 insertions(+), 69 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 1d69980802..5a6f92d8c3 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -18,6 +18,8 @@ The sections below define the target-state runtime contract. Current implementat - Game Session's Account carriers validate and preserve canonical non-nil UUIDs under the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions), including sessions, Account-qualified client requests and presence. Unreadable older session/presence records fail closed without deleting their retained values. This is boundary validation, not Account authorization or an authenticated retained-row mapping. Tenant/catalog carriers, cross-owner UUID support and complete signed-context proof remain unfinished; the Account runtime RPC and first-party credential paths remain denied. Component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). +- `PLAY` resolves a retained catalog tenant key only through Game Session's immutable, approved association under its exact configured workload namespace, then carries that canonical tenant UUID through Account entitlement, membership and grant requests and matching response predicates. Missing configuration, missing associations or contradictory retained evidence deny before admission; the resolver performs no registration or repair. This read-only consequence does not wire the audited association importer, fresh runtime catalog enrollment or complete Account authority. Those activation and proof gates remain open in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + - The unwired Game Session tenant-source client and authored-world intake implementation are packaged in successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923); the prerequisite producer remains in #2915. They consume the separate [Game Design tenant-source read](../game-design-service/api-contracts.md#runtime-tenant-identity-read-for-game-session), requiring file-backed workload mTLS and exact namespace, request and canonical UUID echoes before returning typed provenance. That source read proves neither a retained Game Session numeric-key association nor catalog enrollment, a realm/namespace, a runtime target or admission. Game Session remains the sole persister of its resolved catalog and pointer; canonical UUID intake and propagation into those current numeric carriers remain required before the denied first-party paths can activate. Exact proof and activation limits remain in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 3f25a3c89e..f077813304 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -337,7 +337,7 @@ private GetTenantMembershipForRuntimeResponse membershipAuthorityUnavailable() { public GetTenantEntitlementsForRuntimeResponse getTenantEntitlementsForRuntime( String tenantId, String requestId) { - if (stub() == null) { + if (!AccountIds.isCanonicalNonNilUuid(tenantId) || stub() == null) { return entitlementAuthorityUnavailable(); } GetTenantEntitlementsForRuntimeRequest request = @@ -370,7 +370,9 @@ public GetTenantEntitlementsForRuntimeResponse getTenantEntitlementsForRuntime( public GetRealmAccessGrantForRuntimeResponse getRealmAccessGrantForRuntime( String accountId, String tenantId, String worldSlug, String realmSlug, String requestId) { - if (stub() == null) { + if (!AccountIds.isCanonicalNonNilUuid(accountId) + || !AccountIds.isCanonicalNonNilUuid(tenantId) + || stub() == null) { return realmAccessGrantUnavailable(); } GetRealmAccessGrantForRuntimeRequest request = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index f348441885..b84f5e938c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -37,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -73,6 +74,7 @@ public class PlayCommandHandler { private final GameplayWorldCatalog gameplayWorldCatalog; private final GameLogicProperties gameLogicProperties; private final AccountClient accountClient; + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver; private final EntityManagementClient entityManagementClient; private final ModerationPolicyClient moderationPolicyClient; private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; @@ -89,6 +91,7 @@ public PlayCommandHandler( GameplayWorldCatalog gameplayWorldCatalog, GameLogicProperties gameLogicProperties, AccountClient accountClient, + RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver, EntityManagementClient entityManagementClient, ModerationPolicyClient moderationPolicyClient, FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, @@ -109,6 +112,10 @@ public PlayCommandHandler( this.gameLogicProperties = Objects.requireNonNull(gameLogicProperties, "gameLogicProperties must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); + this.retainedRuntimeTenantUuidResolver = + Objects.requireNonNull( + retainedRuntimeTenantUuidResolver, + "retainedRuntimeTenantUuidResolver must not be null"); this.entityManagementClient = Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.moderationPolicyClient = @@ -232,13 +239,21 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { if (connectScopeFailure.isPresent()) { return connectScopeFailure.get(); } + Optional canonicalTenantId = + retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(selectedRealm.tenantId()); + if (canonicalTenantId.isEmpty() + || !AccountIds.isCanonicalNonNilUuid(canonicalTenantId.orElseThrow().toString())) { + return authorityUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), 0L); + } Optional authorityFailure = validateRuntimeAdmission( context, selectedWorld, selectedRealm, selectedTenantTag, - selection.characterSelector()); + selection.characterSelector(), + canonicalTenantId.orElseThrow()); if (authorityFailure.isPresent()) { return authorityFailure.get(); } @@ -635,7 +650,8 @@ private Optional validateRuntimeAdmission( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag, - String requestedCharacter) { + String requestedCharacter, + UUID canonicalTenantId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); // This is only a denial-cleanup hint for an already bound runtime, never actor admission. long requestedCharacterId = @@ -644,8 +660,7 @@ private Optional validateRuntimeAdmission( ? context.characterId() : 0L; GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime( - Long.toString(selectedRealm.tenantId()), requestId); + accountClient.getTenantEntitlementsForRuntime(canonicalTenantId.toString(), requestId); Optional entitlementFailure = validateEntitlementsResponse( entitlementResponse, @@ -653,14 +668,20 @@ private Optional validateRuntimeAdmission( tenantTag, selectedWorld, selectedRealm, - requestedCharacterId); + requestedCharacterId, + canonicalTenantId.toString()); if (entitlementFailure.isPresent()) { return entitlementFailure; } GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( - membershipPlayerContext(context, selectedRealm, requestedCharacterId, requestId)); + membershipPlayerContext( + context, + selectedRealm, + requestedCharacterId, + requestId, + canonicalTenantId.toString())); return validateMembershipResponse( membershipResponse, context, @@ -669,7 +690,8 @@ private Optional validateRuntimeAdmission( selectedRealm, requestedCharacterId, entitlementResponse.getAllowPublicJoin(), - requestId); + requestId, + canonicalTenantId.toString()); } private long requireResolvedCharacterId(String characterId) { @@ -707,7 +729,8 @@ private Optional validateMembershipResponse( GameplayWorldCatalog.RealmView selectedRealm, long requestedCharacterId, boolean allowPublicJoin, - String requestId) { + String requestId, + String canonicalTenantId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { if (!isAuthorityUnavailable(maybeError.orElseThrow())) { @@ -719,7 +742,8 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (!isSafeMembershipAuthorityResponse(response, context, selectedRealm, requestId)) { + if (!isSafeMembershipAuthorityResponse( + response, context, selectedRealm, canonicalTenantId, requestId)) { return Optional.of( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); @@ -769,7 +793,7 @@ private Optional validateMembershipResponse( GetRealmAccessGrantForRuntimeResponse grantResponse = accountClient.getRealmAccessGrantForRuntime( context.accountId(), - Long.toString(selectedRealm.tenantId()), + canonicalTenantId, selectedWorld.slug(), selectedRealm.slug(), requestId); @@ -779,6 +803,13 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } + if (grantError.isEmpty() + && !isSafeRealmAccessGrantResponse( + grantResponse, context, canonicalTenantId, selectedWorld, selectedRealm)) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (grantError.isPresent() || !grantResponse.getGranted()) { return Optional.of( realmAccessDeniedFailure( @@ -1057,10 +1088,11 @@ private static PlayerExecutionContext membershipPlayerContext( SessionContext caller, GameplayWorldCatalog.RealmView target, long characterId, - String requestId) { + String requestId, + String canonicalTenantId) { return PlayerExecutionContext.newBuilder() .setAccountId(caller.accountId()) - .setTenantId(Long.toString(target.tenantId())) + .setTenantId(canonicalTenantId) .setRealmId(Objects.toString(target.realmId(), "")) .setPlayableStateNamespaceId(Objects.toString(target.playableStateNamespaceId(), "")) .setPlayableStateScope(Objects.toString(target.stateScope(), "")) @@ -1155,7 +1187,8 @@ private Optional validateEntitlementsResponse( String tenantTag, GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, - long requestedCharacterId) { + long requestedCharacterId, + String canonicalTenantId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { if (isEntitlementUnavailable(maybeError.get())) { @@ -1172,7 +1205,7 @@ private Optional validateEntitlementsResponse( tenantBillingBlockedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } - if (!isSafeEntitlementAuthorityResponse(response, selectedRealm)) { + if (!isSafeEntitlementAuthorityResponse(response, canonicalTenantId)) { return Optional.of( entitlementUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); @@ -1301,6 +1334,7 @@ private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, + String canonicalTenantId, String requestId) { if (!"AVAILABLE".equals(response.getAuthorityAvailability()) || !StringUtils.hasText(response.getAccountId()) @@ -1308,8 +1342,9 @@ private boolean isSafeMembershipAuthorityResponse( || !StringUtils.hasText(response.getEvaluatedAt()) || !AccountIds.isCanonicalNonNilUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId()) + || !response.getTenantId().equals(canonicalTenantId) || !response.getRequestAccountId().equals(context.accountId()) - || !response.getRequestTenantId().equals(Long.toString(selectedRealm.tenantId())) + || !response.getRequestTenantId().equals(canonicalTenantId) || !response.getRequestId().equals(requestId)) { return false; } @@ -1326,25 +1361,38 @@ private boolean isSafeMembershipAuthorityResponse( } private boolean isSafeEntitlementAuthorityResponse( - GetTenantEntitlementsForRuntimeResponse response, - GameplayWorldCatalog.RealmView selectedRealm) { + GetTenantEntitlementsForRuntimeResponse response, String canonicalTenantId) { if (!StringUtils.hasText(response.getTenantId()) || !StringUtils.hasText(response.getEvaluatedAt()) || response.getEntitlementVersion() <= 0L) { return false; } try { - long tenantId = Long.parseLong(response.getTenantId()); Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); Instant now = Instant.now(); - return tenantId == selectedRealm.tenantId() + return isCanonicalUuid(response.getTenantId()) + && response.getTenantId().equals(canonicalTenantId) && !evaluatedAt.isAfter(now) && evaluatedAt.isAfter(now.minus(15, ChronoUnit.SECONDS)); - } catch (DateTimeParseException | NumberFormatException ex) { + } catch (DateTimeParseException ex) { return false; } } + private boolean isSafeRealmAccessGrantResponse( + GetRealmAccessGrantForRuntimeResponse response, + SessionContext context, + String canonicalTenantId, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm) { + return AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + && response.getAccountId().equals(context.accountId()) + && isCanonicalUuid(response.getTenantId()) + && response.getTenantId().equals(canonicalTenantId) + && response.getWorldSlug().equals(selectedWorld.slug()) + && response.getRealmSlug().equals(selectedRealm.slug()); + } + private void maybeRecordFreshEntryFallback( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java new file mode 100644 index 0000000000..34a42f6687 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Wires the immutable retained-association store only for the read-only runtime UUID resolver. */ +@Configuration(proxyBeanMethods = false) +public class RetainedRuntimeTenantUuidResolverConfiguration { + @Bean + public RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return RetainedRuntimeTenantUuidResolver.denyOnly(workloadNamespace); + } + GameSessionRetainedTenantAssociationRepository associationRepository = + new GameSessionRetainedTenantAssociationRepository( + dsl, snapshotRepository, workloadNamespace); + return new RetainedRuntimeTenantUuidResolver( + associationRepository, workloadNamespace, transactionManager); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java index c68a76c97e..be214f1811 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java @@ -227,6 +227,62 @@ public Optional read( return Optional.empty(); } + /** + * Reads the canonical tenant UUID for one positive retained Game Session tenant key. + * + *

The lookup is committed-outcome read-only. It validates the complete immutable receipt and + * confirms that the operation, request, canonical UUID, and retained key all cross-read to the + * same association row before returning the UUID. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readCanonicalTenantIdByRetainedTenantKey( + long legacyGameSessionTenantId, String exactNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("Game Session workload namespace is invalid"); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association read requires a committed-outcome owner read"); + } + requirePositive(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requireNamespace(exactNamespace); + if (!workloadNamespace.equals(exactNamespace)) { + throw new IllegalArgumentException( + "exactNamespace must match the configured Game Session workload namespace"); + } + + Record row = findByLegacyKey(exactNamespace, legacyGameSessionTenantId); + if (row == null) { + return Optional.empty(); + } + + AssociationReceipt receipt = toValidatedReceipt(row); + UUID operationId = receipt.operationId(); + UUID associationRequestId = receipt.associationRequestId(); + UUID canonicalTenantId = receipt.approval().canonicalTenantId(); + if (receipt.approval().legacyGameSessionTenantIdValue() != legacyGameSessionTenantId + || !receipt.approval().targetNamespace().equals(exactNamespace)) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant key lookup contradicts its exact namespace or key"); + } + + requireSameAssociationRow(findByOperationId(operationId), operationId, "operation"); + requireSameAssociationRow( + findByRequest(exactNamespace, associationRequestId), operationId, "request"); + requireSameAssociationRow( + findByCanonicalTenant(exactNamespace, canonicalTenantId), operationId, "canonical UUID"); + requireSameAssociationRow( + findByLegacyKey(exactNamespace, legacyGameSessionTenantId), operationId, "retained key"); + return Optional.of(canonicalTenantId); + } + + private void requireSameAssociationRow(Record row, UUID operationId, String identityLabel) { + if (row == null || !operationId.equals(row.get(OPERATION_ID))) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant association " + identityLabel + " cross-read is contradictory"); + } + } + private AssociationReceipt requireExactRetry( Record row, UUID associationRequestId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java new file mode 100644 index 0000000000..f726b006ef --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Read-only resolver for approved UUID associations to retained Game Session tenant keys. */ +public final class RetainedRuntimeTenantUuidResolver { + private static final Logger LOG = + LoggerFactory.getLogger(RetainedRuntimeTenantUuidResolver.class); + + private final GameSessionRetainedTenantAssociationRepository associationRepository; + private final String workloadNamespace; + private final TransactionTemplate committedOutcomeRead; + + public RetainedRuntimeTenantUuidResolver( + GameSessionRetainedTenantAssociationRepository associationRepository, + String workloadNamespace, + PlatformTransactionManager transactionManager) { + this.workloadNamespace = Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.committedOutcomeRead = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.committedOutcomeRead.setPropagationBehavior( + TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + this.committedOutcomeRead.setReadOnly(true); + } + + private RetainedRuntimeTenantUuidResolver(String workloadNamespace) { + this.associationRepository = null; + this.workloadNamespace = workloadNamespace; + this.committedOutcomeRead = null; + } + + /** Creates an unavailable resolver when the configured namespace is absent or malformed. */ + public static RetainedRuntimeTenantUuidResolver denyOnly(String workloadNamespace) { + if (workloadNamespace != null && GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("A valid namespace cannot use the deny-only resolver"); + } + return new RetainedRuntimeTenantUuidResolver(workloadNamespace); + } + + /** Resolves only the exact configured-namespace association; all uncertainty fails closed. */ + public Optional resolveCanonicalTenantId(long legacyGameSessionTenantId) { + if (legacyGameSessionTenantId <= 0L || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return Optional.empty(); + } + if (associationRepository == null || committedOutcomeRead == null) { + return Optional.empty(); + } + try { + return Objects.requireNonNull( + committedOutcomeRead.execute( + status -> + associationRepository.readCanonicalTenantIdByRetainedTenantKey( + legacyGameSessionTenantId, workloadNamespace))); + } catch (RuntimeException exception) { + LOG.warn("Retained runtime tenant UUID association is unavailable", exception); + return Optional.empty(); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index 244c1b387a..d9c7b1a3ec 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -135,6 +135,111 @@ void committedReadRejectsForeignNamespaceBeforeDatabaseAccess() { verifyNoInteractions(dsl, snapshots); } + @Test + void retainedKeyLookupReturnsHistoricalUuidOnlyForExactNamespaceAndKey() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-before-association"); + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, snapshot); + fixture.register(uuid(301), approval); + + assertThat(fixture.repository.readCanonicalTenantIdByRetainedTenantKey(42L, NAMESPACE)) + .contains(uuid(201)); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.repository.readCanonicalTenantIdByRetainedTenantKey( + 42L, NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.repository.readCanonicalTenantIdByRetainedTenantKey(999L, NAMESPACE)) + .isEmpty(); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-association", + 420L); + assertThat(fixture.repository.readCanonicalTenantIdByRetainedTenantKey(42L, NAMESPACE)) + .contains(uuid(201)); + + GameSessionRetainedTenantAssociationRepository foreignNamespaceRepository = + new GameSessionRetainedTenantAssociationRepository( + fixture.dsl, fixture.snapshotRepository, "other-namespace"); + assertThat( + foreignNamespaceRepository.readCanonicalTenantIdByRetainedTenantKey( + 42L, "other-namespace")) + .isEmpty(); + assertThatThrownBy( + () -> + fixture.repository.readCanonicalTenantIdByRetainedTenantKey(42L, "other-namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session workload namespace"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows() { + Fixture malformedFixture = fixture(); + malformedFixture.seedInstance(42L, 420L, "runtime-malformed"); + malformedFixture.register( + uuid(301), + malformedFixture.approval(uuid(101), uuid(201), 42L, malformedFixture.capture(42L))); + disableAssociationImmutabilityTrigger(malformedFixture); + try { + malformedFixture.dsl.execute( + "UPDATE game_session_retained_tenant_association SET approved_by = ? " + + "WHERE target_namespace = ? AND legacy_game_session_tenant_id = ?", + "changed-reviewer", + NAMESPACE, + 42L); + } finally { + enableAssociationImmutabilityTrigger(malformedFixture); + } + assertThatThrownBy( + () -> + malformedFixture.repository.readCanonicalTenantIdByRetainedTenantKey( + 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + + Fixture contradictoryFixture = fixture(); + contradictoryFixture.seedInstance(43L, 430L, "runtime-contradictory"); + contradictoryFixture.register( + uuid(302), + contradictoryFixture.approval( + uuid(102), uuid(202), 43L, contradictoryFixture.capture(43L))); + disableAssociationImmutabilityTrigger(contradictoryFixture); + try { + contradictoryFixture.dsl.execute( + "UPDATE game_session_retained_tenant_association " + + "SET legacy_game_session_tenant_id = ? " + + "WHERE target_namespace = ? AND legacy_game_session_tenant_id = ?", + 44L, + NAMESPACE, + 43L); + } finally { + enableAssociationImmutabilityTrigger(contradictoryFixture); + } + assertThatThrownBy( + () -> + contradictoryFixture.repository.readCanonicalTenantIdByRetainedTenantKey( + 44L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + } + + private void disableAssociationImmutabilityTrigger(Fixture fixture) { + fixture.dsl.execute( + "ALTER TABLE game_session_retained_tenant_association " + + "DISABLE TRIGGER game_session_retained_tenant_association_immutable"); + } + + private void enableAssociationImmutabilityTrigger(Fixture fixture) { + fixture.dsl.execute( + "ALTER TABLE game_session_retained_tenant_association " + + "ENABLE TRIGGER game_session_retained_tenant_association_immutable"); + } + @Test void changedRequestAndOneToOneClaimConflictsLeaveNoPartialRows() { Fixture fixture = fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 9cef9d2d76..794de471f0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -47,6 +47,8 @@ import org.mockito.ArgumentCaptor; class AccountClientTest { + private static final String ACCOUNT_UUID = "9b80a81b-7971-44af-bd6b-18079027f47a"; + private static final String TENANT_UUID = "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1"; @Test void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() throws Exception { @@ -413,7 +415,9 @@ void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exce @Test void realmAccessGrantReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetRealmAccessGrantForRuntimeResponse response = - newClient(null).getRealmAccessGrantForRuntime("42", "7", "world", "realm", "request-1"); + newClient(null) + .getRealmAccessGrantForRuntime( + ACCOUNT_UUID, TENANT_UUID, "world", "realm", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Realm grant authority unavailable"); @@ -498,7 +502,7 @@ void runtimeMembershipNormalizesExhaustedUnavailableToCanonicalUnavailable() thr @Test void runtimeEntitlementsReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetTenantEntitlementsForRuntimeResponse response = - newClient(null).getTenantEntitlementsForRuntime("7", "request-1"); + newClient(null).getTenantEntitlementsForRuntime(TENANT_UUID, "request-1"); assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.getError().getMessage()).isEqualTo("Entitlement authority unavailable"); @@ -517,7 +521,7 @@ void runtimeEntitlementsNormalizesExhaustedUnavailableToCanonicalUnavailable() t .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantEntitlementsForRuntimeResponse response = - fixture.client().getTenantEntitlementsForRuntime("7", "request-1"); + fixture.client().getTenantEntitlementsForRuntime(TENANT_UUID, "request-1"); assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.getError().getMessage()).isEqualTo("Entitlement authority unavailable"); @@ -528,6 +532,103 @@ void runtimeEntitlementsNormalizesExhaustedUnavailableToCanonicalUnavailable() t verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @Test + void runtimeEntitlementsForwardsExactCanonicalTenantUuid() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + GetTenantEntitlementsForRuntimeResponse expected = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId(TENANT_UUID) + .setGameplayAvailable(true) + .build(); + when(stub.getTenantEntitlementsForRuntime(any(GetTenantEntitlementsForRuntimeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + + assertThat(client.getTenantEntitlementsForRuntime(TENANT_UUID, "request-1")) + .isEqualTo(expected); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(GetTenantEntitlementsForRuntimeRequest.class); + verify(stub).getTenantEntitlementsForRuntime(captor.capture()); + assertThat(captor.getValue().getTenantId()).isEqualTo(TENANT_UUID); + } + + @ParameterizedTest + @ValueSource( + strings = { + "7", + "not-a-uuid", + "CC5E6D40-88C0-4F91-A6D3-A738F4F2F0A1", + "00000000-0000-0000-0000-000000000000", + "" + }) + void runtimeEntitlementsRejectsInvalidTenantUuidBeforeStubOrChannelUse(String tenantId) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountClient client = newClient(stub, channelFactory); + + GetTenantEntitlementsForRuntimeResponse response = + client.getTenantEntitlementsForRuntime(tenantId, "request-1"); + + assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(stub, channelFactory); + } + + @Test + void realmAccessGrantForwardsExactCanonicalAccountAndTenantUuids() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + GetRealmAccessGrantForRuntimeResponse expected = + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId(TENANT_UUID) + .setWorldSlug("world") + .setRealmSlug("realm") + .setGranted(true) + .build(); + when(stub.getRealmAccessGrantForRuntime(any(GetRealmAccessGrantForRuntimeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + + assertThat( + client.getRealmAccessGrantForRuntime( + ACCOUNT_UUID, TENANT_UUID, "world", "realm", "request-1")) + .isEqualTo(expected); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(GetRealmAccessGrantForRuntimeRequest.class); + verify(stub).getRealmAccessGrantForRuntime(captor.capture()); + assertThat(captor.getValue().getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(captor.getValue().getTenantId()).isEqualTo(TENANT_UUID); + } + + @ParameterizedTest + @CsvSource({ + "42, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "not-a-uuid, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, 7", + "9B80A81B-7971-44AF-BD6B-18079027F47A, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, 00000000-0000-0000-0000-000000000000" + }) + void realmAccessGrantRejectsInvalidUuidInputsBeforeStubOrChannelUse( + String accountId, String tenantId) throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountClient client = newClient(stub, channelFactory); + + GetRealmAccessGrantForRuntimeResponse response = + client.getRealmAccessGrantForRuntime(accountId, tenantId, "world", "realm", "request-1"); + + assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + verifyNoInteractions(stub, channelFactory); + } + @Test void realmAccessGrantNormalizesExhaustedUnavailableToCanonicalUnavailable() throws Exception { RetryFixture fixture = newRetryFixture(); @@ -541,7 +642,10 @@ void realmAccessGrantNormalizesExhaustedUnavailableToCanonicalUnavailable() thro .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetRealmAccessGrantForRuntimeResponse response = - fixture.client().getRealmAccessGrantForRuntime("42", "7", "world", "realm", "request-1"); + fixture + .client() + .getRealmAccessGrantForRuntime( + ACCOUNT_UUID, TENANT_UUID, "world", "realm", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Realm grant authority unavailable"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 363428efd6..62da95cdcc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -16,6 +16,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -34,6 +35,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -55,12 +57,15 @@ class LoginCommandHandlerTest { private static final String ACCOUNT_77 = "774f987b-6650-4d04-8e0f-441867c17923"; private static final String ACCOUNT_99 = "998a7412-13c4-4dbc-86d9-8f40aee3c6f1"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; private final GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry = Mockito.mock(FirstPartyConnectContextRegistry.class); private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService = @@ -74,6 +79,8 @@ class LoginCommandHandlerTest { @BeforeEach void setUp() { + Mockito.when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); meterRegistry.clear(); stubSessionContext(bootstrapShell(1L, 1L)); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) @@ -1740,6 +1747,7 @@ private PlayCommandHandler createPlayCommandHandler() { GameplayWorldCatalog.forWorldViews(List.of()), new GameLogicProperties(), accountClient, + retainedRuntimeTenantUuidResolver, Mockito.mock(EntityManagementClient.class), Mockito.mock(ModerationPolicyClient.class), firstPartyConnectContextRegistry, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 4b83c987f4..5be1829f27 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -11,9 +11,11 @@ import java.io.IOException; import java.time.Instant; 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 net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; @@ -35,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -53,6 +56,8 @@ class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; private static final String PLAYER_ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; + private static final String FIXTURE_LEGACY_TENANT_UUID = "00000000-0000-0000-0000-000000000022"; private static final ObjectMapper JSON = new ObjectMapper(); private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); @@ -61,6 +66,8 @@ class PlayCommandHandlerTest { private final SessionRoutingNormalizationService sessionRoutingNormalizationService = Mockito.mock(SessionRoutingNormalizationService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final ModerationPolicyClient moderationPolicyClient = @@ -101,12 +108,15 @@ void setUp() { worldCatalog, gameLogicProperties, accountClient, + retainedRuntimeTenantUuidResolver, entityManagementClient, moderationPolicyClient, firstPartyConnectContextRegistry, gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -125,7 +135,7 @@ void setUp() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -138,7 +148,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(grantResponse(true)); when(sessionRoutingNormalizationService.normalizeProjectedContext( Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -157,6 +167,100 @@ void setUp() { }); } + @Test + void playForwardsResolvedUuidAndKeepsCatalogKeyForLocalRosterLookup() { + SessionContext context = + new SessionContext( + 1L, 93L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("123", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + var membershipCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + Mockito.verify(accountClient).getTenantMembershipForRuntime(membershipCaptor.capture()); + assertThat(membershipCaptor.getValue().getTenantId()).isEqualTo(CANONICAL_TENANT_UUID); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); + Mockito.verify(retainedRuntimeTenantUuidResolver).resolveCanonicalTenantId(22L); + Mockito.verify(retainedRuntimeTenantUuidResolver, never()).resolveCanonicalTenantId(93L); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(sessionContextService).save(Mockito.argThat(saved -> saved.tenantId() == 22L)); + } + + @Test + void missingRetainedUuidAssociationDeniesBeforeAccountOrGameplayAccess() { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, sessionContextService); + Mockito.verifyNoInteractions( + gameplayPresenceLifecycleService, moderationPolicyClient, scriptEventPublisher); + } + + @Test + void malformedRetainedUuidAssociationDeniesBeforeAccountOrGameplayAccess() { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(new UUID(0L, 0L))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, sessionContextService); + Mockito.verifyNoInteractions( + gameplayPresenceLifecycleService, moderationPolicyClient, scriptEventPublisher); + } + + @ParameterizedTest + @ValueSource(strings = {"22", "6c118f15-ceda-4f7e-bf9f-1c342cb83962"}) + void numericOrWrongTenantEchoDeniesBeforeRosterOrBinding(String responseTenantId) { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(PLAYER_ACCOUNT_ID, 22L, "1")); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + response.toBuilder().setTenantId(responseTenantId).build(), + invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService, scriptEventPublisher); + } + @Test void playPromotesSessionIntoGameplay() { SessionContext context = @@ -619,7 +723,7 @@ void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); order .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); order .verify(accountClient) .getTenantMembershipForRuntime( @@ -628,7 +732,7 @@ void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { .verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1521,7 +1625,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(grantResponse(true)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1529,7 +1633,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1545,7 +1649,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(grantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1569,7 +1673,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1582,7 +1686,7 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) @@ -1596,7 +1700,7 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1613,7 +1717,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(grantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -2028,7 +2132,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { ? GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE : GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); Mockito.verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); Mockito.verify(accountClient, never()) .getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); @@ -2062,7 +2166,7 @@ void playBillingDenialMasksMissingPublicMembership() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(false) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -2108,7 +2212,7 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) @@ -2150,7 +2254,7 @@ void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) @@ -2191,7 +2295,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -2205,7 +2309,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); Mockito.verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); Mockito.verify(accountClient) .getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); @@ -2597,7 +2701,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) @@ -3011,8 +3115,7 @@ private static String resealWithMembershipVersion( String canonicalJson, String membershipVersion) { try { ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); - ((ObjectNode) event.get("membershipVersion")) - .put("00000000-0000-0000-0000-000000000022", membershipVersion); + ((ObjectNode) event.get("membershipVersion")).put(CANONICAL_TENANT_UUID, membershipVersion); event.remove("eventDigest"); return MembershipAuthorityEventV1Codec.seal( JSON.convertValue(event, new TypeReference>() {})) @@ -3034,7 +3137,131 @@ private static String changeCanonicalEventWithoutResealing(String canonicalJson) private static GetTenantMembershipForRuntimeResponse freshMembership( GetTenantMembershipForRuntimeResponse response) { - return response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); + String originalTenantId = response.getTenantId(); + var builder = + response.toBuilder() + .setTenantId(CANONICAL_TENANT_UUID) + .setRequestTenantId(CANONICAL_TENANT_UUID) + .setEvaluatedAt(Instant.now().toString()); + if (response.getMembershipVersionCount() > 0) { + builder + .clearMembershipVersion() + .putAllMembershipVersion(rekeyMap(response.getMembershipVersionMap(), originalTenantId)); + } + if (response.hasMembershipBaseline()) { + builder.setMembershipBaseline( + response.getMembershipBaseline().toBuilder() + .clearMembershipVersion() + .putAllMembershipVersion( + rekeyMap( + response.getMembershipBaseline().getMembershipVersionMap(), originalTenantId)) + .build()); + } + if (response.hasAuthorityTuple()) { + var tuple = response.getAuthorityTuple().toBuilder(); + tuple + .clearTenantAuthorityGeneration() + .putAllTenantAuthorityGeneration( + rekeyMap( + response.getAuthorityTuple().getTenantAuthorityGenerationMap(), + originalTenantId)); + tuple + .clearMembershipAuthorityGeneration() + .putAllMembershipAuthorityGeneration( + rekeyMap( + response.getAuthorityTuple().getMembershipAuthorityGenerationMap(), + originalTenantId)); + for (int index = 0; + index < response.getAuthorityTuple().getPrivateRealmGrantVersionsCount(); + index++) { + var grant = response.getAuthorityTuple().getPrivateRealmGrantVersions(index); + if (originalTenantId.equals(grant.getTenantId())) { + tuple.setPrivateRealmGrantVersions( + index, grant.toBuilder().setTenantId(CANONICAL_TENANT_UUID).build()); + } + } + builder.setAuthorityTuple(tuple.build()); + } + builder.clearOutboxCheckpoints(); + response + .getOutboxCheckpointsList() + .forEach( + checkpoint -> + builder.addOutboxCheckpoints( + checkpoint.toBuilder() + .setOutboxStreamKey( + rekeyPathTenant(checkpoint.getOutboxStreamKey(), originalTenantId)) + .build())); + builder.clearOutboxSourceEvidence(); + response + .getOutboxSourceEvidenceList() + .forEach( + source -> { + String canonicalEventJson = + rekeyMembershipEvent( + source.getCanonicalEventJson(), response.getAccountId(), originalTenantId); + var event = MembershipAuthorityEventV1Codec.verify(canonicalEventJson); + builder.addOutboxSourceEvidence( + source.toBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build()); + }); + return builder.build(); + } + + private static Map rekeyMap(Map values, String originalTenantId) { + Map result = new LinkedHashMap<>(); + values.forEach( + (key, value) -> { + String rekeyed = originalTenantId.equals(key) ? CANONICAL_TENANT_UUID : key; + if (result.putIfAbsent(rekeyed, value) != null) { + throw new IllegalArgumentException("Fixture tenant UUID rekey collides"); + } + }); + return result; + } + + private static String rekeyPathTenant(String value, String originalTenantId) { + return value.replace("/" + originalTenantId, "/" + CANONICAL_TENANT_UUID); + } + + private static String rekeyMembershipEvent( + String canonicalJson, String accountId, String originalTenantId) { + try { + ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); + event.put("tenantId", CANONICAL_TENANT_UUID); + event.put( + "outboxStreamKey", + rekeyPathTenant(event.path("outboxStreamKey").asText(), originalTenantId)); + event.put("sourceScope", "membership/" + accountId + "/" + CANONICAL_TENANT_UUID); + rekeyJsonMap((ObjectNode) event.get("membershipVersion"), originalTenantId); + ObjectNode tuple = (ObjectNode) event.get("authorityTuple"); + rekeyJsonMap((ObjectNode) tuple.get("tenantAuthorityGeneration"), originalTenantId); + rekeyJsonMap((ObjectNode) tuple.get("membershipAuthorityGeneration"), originalTenantId); + if (tuple.has("privateRealmGrantVersions")) { + for (var grant : tuple.withArray("privateRealmGrantVersions")) { + if (grant instanceof ObjectNode grantObject + && originalTenantId.equals(grantObject.path("tenantId").asText())) { + grantObject.put("tenantId", CANONICAL_TENANT_UUID); + } + } + } + event.remove("eventDigest"); + return MembershipAuthorityEventV1Codec.seal( + JSON.convertValue(event, new TypeReference>() {})) + .canonicalJson(); + } catch (IOException ex) { + throw new AssertionError("test event should be valid JSON", ex); + } + } + + private static void rekeyJsonMap(ObjectNode values, String originalTenantId) { + if (values != null && values.has(originalTenantId)) { + var value = values.remove(originalTenantId); + values.set(CANONICAL_TENANT_UUID, value); + } } private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(String defect) { @@ -3113,6 +3340,16 @@ private static Character actor(String id, String name, PlayableStateScope scope) .build(); } + private static GetRealmAccessGrantForRuntimeResponse grantResponse(boolean granted) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(PLAYER_ACCOUNT_ID) + .setTenantId(CANONICAL_TENANT_UUID) + .setWorldSlug("sandbox") + .setRealmSlug("preview") + .setGranted(granted) + .build(); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 1a629d3d89..d9b5e4b3a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -57,6 +58,7 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -74,6 +76,7 @@ @SuppressWarnings("unchecked") class SessionResumptionFlowTest { private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; private static final String PLAY_PAYLOAD = "PLAY demo"; private static final String LOOK_PAYLOAD = "LOOK"; @@ -82,6 +85,8 @@ class SessionResumptionFlowTest { private final GameInstanceRepository instanceRepository = Mockito.mock(GameInstanceRepository.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final ModerationPolicyClient moderationPolicyClient = @@ -141,6 +146,8 @@ class SessionResumptionFlowTest { @BeforeEach void setUp() { + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); sessionContextService.save(bootstrapShell(1L, 1L)); sessionContextService.save(bootstrapShell(2L, 1L)); gameplayCatalogProperties.setWorlds( @@ -173,7 +180,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - "550e8400-e29b-41d4-a716-446655440000", 22L, "1") + "550e8400-e29b-41d4-a716-446655440000", 22L, CANONICAL_TENANT_UUID, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -186,7 +193,15 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setGranted(true) + .setAccountId(invocation.getArgument(0)) + .setTenantId(invocation.getArgument(1)) + .setWorldSlug(invocation.getArgument(2)) + .setRealmSlug(invocation.getArgument(3)) + .build()); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -195,7 +210,7 @@ void setUp() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -285,6 +300,7 @@ void setUp() { worldCatalog, gameLogicProperties, accountClient, + retainedRuntimeTenantUuidResolver, entityManagementClient, moderationPolicyClient, firstPartyConnectContextRegistry, @@ -465,21 +481,11 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .thenAnswer( invocation -> { var response = - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - "550e8400-e29b-41d4-a716-446655440000", 22L, "2"); + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .activeWithoutPlayerRole( + "550e8400-e29b-41d4-a716-446655440000", 22L, CANONICAL_TENANT_UUID, "2"); var deniedResponse = - response.toBuilder() - .setGameplayAdmissionAllowed(false) - .setMembershipAuthorityGeneration("2") - .setMembershipBaseline( - response.getMembershipBaseline().toBuilder() - .setMembershipAuthorityGeneration("2")) - .setAuthorityTuple( - response.getAuthorityTuple().toBuilder() - .putMembershipAuthorityGeneration( - "00000000-0000-0000-0000-000000000022", "2")) - .setEvaluatedAt(Instant.now().toString()) - .build(); + response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId(deniedResponse, invocation.getArgument(0)); }); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 5de6687712..93f1be3a34 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -72,6 +73,7 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -89,6 +91,7 @@ class TextCommandInterpreterTest { private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; private final CommandService commandService = Mockito.mock(CommandService.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final EntityManagementClient entityManagementClient = @@ -106,6 +109,8 @@ class TextCommandInterpreterTest { private final SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); private final LookCacheService lookCacheService = Mockito.mock(LookCacheService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final ModerationPolicyClient moderationPolicyClient = Mockito.mock(ModerationPolicyClient.class); private final MoveCommandHandler moveHandler = Mockito.mock(MoveCommandHandler.class); @@ -157,6 +162,8 @@ class TextCommandInterpreterTest { @BeforeEach void setUp() { + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); sessionContextService.save(bootstrapShell(1L, 1L)); meterRegistry.clear(); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) @@ -171,7 +178,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - ACCOUNT_ID, 22L, "1") + ACCOUNT_ID, 22L, CANONICAL_TENANT_UUID, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -184,7 +191,15 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setGranted(true) + .setAccountId(invocation.getArgument(0)) + .setTenantId(invocation.getArgument(1)) + .setWorldSlug(invocation.getArgument(2)) + .setRealmSlug(invocation.getArgument(3)) + .build()); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -193,7 +208,7 @@ void setUp() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) @@ -376,6 +391,7 @@ void setUp() { worldCatalog, gameLogicProperties, accountClient, + retainedRuntimeTenantUuidResolver, entityManagementClient, moderationPolicyClient, firstPartyConnectContextRegistry, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java new file mode 100644 index 0000000000..63bfe78e02 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java @@ -0,0 +1,104 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.config.RetainedRuntimeTenantUuidResolverConfiguration; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class RetainedRuntimeTenantUuidResolverTest { + private static final String WORKLOAD_NAMESPACE = "gamesession-test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("7c958a3d-401e-47ee-8df8-351988b6ce26"); + + private final GameSessionRetainedTenantAssociationRepository repository = + mock(GameSessionRetainedTenantAssociationRepository.class); + private final PlatformTransactionManager transactionManager = new ReadOnlyTransactionManager(); + + @Test + void resolvesOnlyTheConfiguredNamespaceAndExactPositiveRetainedKey() { + when(repository.readCanonicalTenantIdByRetainedTenantKey(42L, WORKLOAD_NAMESPACE)) + .thenReturn(Optional.of(CANONICAL_TENANT_ID)); + RetainedRuntimeTenantUuidResolver resolver = + new RetainedRuntimeTenantUuidResolver(repository, WORKLOAD_NAMESPACE, transactionManager); + + assertThat(resolver.resolveCanonicalTenantId(42L)).contains(CANONICAL_TENANT_ID); + + verify(repository).readCanonicalTenantIdByRetainedTenantKey(42L, WORKLOAD_NAMESPACE); + } + + @Test + void missingNamespaceOrNonPositiveRetainedKeyDoesNotQueryTheRepository() { + RetainedRuntimeTenantUuidResolver missingNamespace = + RetainedRuntimeTenantUuidResolver.denyOnly(""); + RetainedRuntimeTenantUuidResolver configured = + new RetainedRuntimeTenantUuidResolver(repository, WORKLOAD_NAMESPACE, transactionManager); + RetainedRuntimeTenantUuidResolver invalidNamespace = + RetainedRuntimeTenantUuidResolver.denyOnly("Bad.Namespace"); + + assertThat(missingNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(invalidNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(RetainedRuntimeTenantUuidResolver.denyOnly(null).resolveCanonicalTenantId(42L)) + .isEmpty(); + assertThat(configured.resolveCanonicalTenantId(0L)).isEmpty(); + assertThat(configured.resolveCanonicalTenantId(-1L)).isEmpty(); + + verifyNoInteractions(repository); + } + + @Test + void configurationWithMissingOrInvalidNamespaceConstructsOnlyDenyOnlyResolvers() { + RetainedRuntimeTenantUuidResolverConfiguration configuration = + new RetainedRuntimeTenantUuidResolverConfiguration(); + + RetainedRuntimeTenantUuidResolver missingNamespace = + configuration.retainedRuntimeTenantUuidResolver(null, null, null, ""); + RetainedRuntimeTenantUuidResolver invalidNamespace = + configuration.retainedRuntimeTenantUuidResolver(null, null, null, "Bad.Namespace"); + + assertThat(missingNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(invalidNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + } + + @Test + void repositoryFailureAndMissingAssociationRemainUnavailable() { + RetainedRuntimeTenantUuidResolver resolver = + new RetainedRuntimeTenantUuidResolver(repository, WORKLOAD_NAMESPACE, transactionManager); + when(repository.readCanonicalTenantIdByRetainedTenantKey(42L, WORKLOAD_NAMESPACE)) + .thenThrow(new IllegalStateException("malformed retained receipt")); + when(repository.readCanonicalTenantIdByRetainedTenantKey(43L, WORKLOAD_NAMESPACE)) + .thenReturn(Optional.empty()); + + assertThat(resolver.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(resolver.resolveCanonicalTenantId(43L)).isEmpty(); + } + + private static final class ReadOnlyTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition effectiveDefinition = + definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(effectiveDefinition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + assertThat(effectiveDefinition.isReadOnly()).isTrue(); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index 3e33f9e3a4..0a75e0dc33 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; @@ -26,6 +27,52 @@ public static GetTenantMembershipForRuntimeResponse active( return complete(accountId, tenantId, true, "ACTIVE", true, membershipVersion); } + /** Builds a complete membership carrier for an explicitly supplied canonical tenant UUID. */ + public static GetTenantMembershipForRuntimeResponse active( + String accountId, + long retainedTenantKey, + String canonicalTenantId, + String membershipVersion) { + requireCanonicalTenantId(canonicalTenantId); + requirePositiveRetainedTenantKey(retainedTenantKey); + return completeWithTenant( + accountId, + canonicalTenantId, + canonicalTenantId, + true, + "ACTIVE", + true, + membershipVersion, + "1", + "1", + "1", + false, + List.of("player")); + } + + /** Builds complete active membership authority with no player role for denial-path tests. */ + public static GetTenantMembershipForRuntimeResponse activeWithoutPlayerRole( + String accountId, + long retainedTenantKey, + String canonicalTenantId, + String membershipVersion) { + requireCanonicalTenantId(canonicalTenantId); + requirePositiveRetainedTenantKey(retainedTenantKey); + return completeWithTenant( + accountId, + canonicalTenantId, + canonicalTenantId, + true, + "ACTIVE", + true, + membershipVersion, + "1", + "1", + "1", + false, + List.of("designer")); + } + public static GetTenantMembershipForRuntimeResponse missing(String accountId, long tenantId) { return complete(accountId, tenantId, false, "MISSING", false, "1"); } @@ -115,8 +162,36 @@ private static GetTenantMembershipForRuntimeResponse complete( String outboxSequence, boolean callerBoundAuthorityInvalidated, List roles) { - String accountUuid = accountId; String tenantUuid = uuid(tenantId); + return completeWithTenant( + accountId, + tenantUuid, + Long.toString(tenantId), + exists, + lifecycle, + admitted, + membershipVersion, + membershipAuthorityGeneration, + issuanceFence, + outboxSequence, + callerBoundAuthorityInvalidated, + roles); + } + + private static GetTenantMembershipForRuntimeResponse completeWithTenant( + String accountId, + String tenantUuid, + String requestTenantId, + boolean exists, + String lifecycle, + boolean admitted, + String membershipVersion, + String membershipAuthorityGeneration, + String issuanceFence, + String outboxSequence, + boolean callerBoundAuthorityInvalidated, + List roles) { + String accountUuid = accountId; String membershipStream = STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = new ArrayList<>( @@ -145,7 +220,7 @@ private static GetTenantMembershipForRuntimeResponse complete( .setAccountId(accountUuid) .setTenantId(tenantUuid) .setRequestAccountId(accountId) - .setRequestTenantId(Long.toString(tenantId)) + .setRequestTenantId(requestTenantId) .setAuthorityAvailability("AVAILABLE") .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) @@ -203,6 +278,21 @@ private static GetTenantMembershipForRuntimeResponse complete( return response.build(); } + private static void requireCanonicalTenantId(String tenantId) { + if (tenantId == null + || tenantId.isBlank() + || !UUID.fromString(tenantId).toString().equals(tenantId) + || new UUID(0L, 0L).toString().equals(tenantId)) { + throw new IllegalArgumentException("test canonical tenant ID must be a non-nil UUID"); + } + } + + private static void requirePositiveRetainedTenantKey(long retainedTenantKey) { + if (retainedTenantKey <= 0L) { + throw new IllegalArgumentException("test retained tenant key must be positive"); + } + } + private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String sequence) { return RuntimeOutboxCheckpoint.newBuilder() .setOutboxStreamKey(streamKey) From 933dde7f6951fd040c26864acdb6165f7726a43d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:29:05 +1300 Subject: [PATCH 03/22] Separate issuer projection evidence from recipient authorization --- ...0022-account-authority-and-gameplay-session-ownership.md | 4 ++-- .../adr-0030-risk-based-active-session-revocation.md | 4 ++-- design/architecture/system-architecture-authentication.md | 6 ++++-- .../implementation-tracking/player-access-and-session.md | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md index a786d277b2..4100164bca 100644 --- a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md +++ b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md @@ -52,13 +52,13 @@ Later clarification: [ADR 0132](./adr-0132-namespace-scoped-single-character-con Game Session consumes authoritative Account membership, entitlement, and revocation state. It stores only the token identity and freshness metadata needed to validate a binding, such as token hash, issued-at time, and `membershipVersion`; it must not make a persisted raw backend JWT the durable session authority. -For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its schema is `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. The issuer source event and the recipient evidence it affects remain separate under [Authentication's source-event contract](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence): source events bind issuer scope and committed source progress, while Account readback binds the consumed event/checkpoint to the recipient's complete `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one snapshot. The source event is not required to carry that recipient tuple or fence. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained source evidence or an exact Account checkpoint lookup proves the same event identity/digest, source sequence, exact stream key, and issuer source progress, and the Account recipient readback proves the complete same-snapshot `authorityTuple`, positive `issuanceFence`, and complete `outboxCheckpoints` set. A source-event match without that recipient binding is not duplicate proof. Missing, partial, generation-only, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same source-event and recipient-binding comparison before the watermark or generation advances; a lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. This local projection is a revocation-consumer cache, not an authority source, and Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. +For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its schema is `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. The issuer source event and any recipient evidence it affects remain separate under [Authentication's source-event contract](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence). For this derived issuer projection, bootstrap, advancement, and duplicate verification use Account-authenticated evidence for the exact issuer scope and source checkpoint: exact issuer and stream identity, committed issuer generation and source version, sequence, and complete applicable source-event identity, payload, and digest. No individual recipient's `authorityTuple`, actual `issuanceFence`, or complete `outboxCheckpoints` set is a prerequisite for maintaining this projection. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained source evidence or an exact Account checkpoint lookup proves the same complete event identity, payload, and digest, source sequence, exact stream key, and issuer source progress; generation-only equality is insufficient. Missing, partial, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same exact source/checkpoint comparison before the watermark or generation advances, and the projection watermark and corresponding source/checkpoint evidence are updated atomically. A lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. The projection is a revocation-consumer cache, not an authority source: it grants no admission or rebind authority. Any individual recipient authorization, admission, or rebind still requires the complete Account-authenticated recipient binding, including the applicable `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set, from one snapshot. Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. ### Canonical Checkpoint And Source-Evidence Binding [ADR 0030](./adr-0030-risk-based-active-session-revocation.md) owns the unchanged `outboxCheckpoints` entry schema: exactly `{outboxStreamKey, outboxSequence}`, with one entry for every applicable authority stream. `compareOutboxCheckpointEntries(a, b)` compares the unsigned UTF-8 bytes of `outboxStreamKey` lexicographically and places the shorter key first when one is a prefix. Duplicate stream keys, locale collation, Unicode normalization, case folding, alternate escaping, or another ordering are invalid. -Event identity, digest, and stream position remain source evidence separate from the `outboxCheckpoints` carrier. For each checkpoint, an Account-authenticated same-snapshot readback binds the consumed source event evidence to the recipient's complete `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one Account linearization point. Scope-wide issuer/account/tenant source events are not required to carry that recipient tuple or fence; the closed membership event retains the exact fields declared by its v1 schema. Delivery, refresh, rebind, binding CAS, acknowledgement, retries, and duplicate detection carry or resolve the complete recipient binding and exact source evidence without adding fields to the checkpoint carrier. A latest entry, aggregate maximum, projection-only value, partial source-evidence match, or evidence assembled from separate snapshots is invalid and quarantines the affected scope. +Event identity, digest, and stream position remain source evidence separate from the `outboxCheckpoints` carrier. For recipient authority, an Account-authenticated same-snapshot readback binds the consumed source event evidence to the recipient's complete `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one Account linearization point. Scope-wide issuer/account/tenant source events are not required to carry that recipient tuple or fence; issuer projection maintenance consumes its exact authenticated issuer source/checkpoint evidence without an individual recipient binding. The closed membership event retains the exact fields declared by its v1 schema. Delivery, refresh, rebind, binding CAS, acknowledgement, retries, and duplicate detection for recipient authority carry or resolve the complete recipient binding and exact source evidence without adding fields to the checkpoint carrier. A latest entry, aggregate maximum, issuer projection alone, partial source-evidence match, or evidence assembled from separate snapshots cannot satisfy recipient authority and quarantines the affected recipient scope. ### Operation Partition diff --git a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md index 9574e50d04..6236a7dfb5 100644 --- a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md +++ b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md @@ -28,7 +28,7 @@ The previous target distinguished soft and hard billing states and required even ### Canonical Authority Tuple Boundary -[JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to Account-authenticated recipient authority evidence, revocation-local admission decisions, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite recipient fence copied alongside the tuple, never a substitute for a tuple member. [Authentication](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence) owns the distinction between scope-wide source events and recipient evidence: Account readback binds consumed source evidence to the recipient tuple and fence from one snapshot. The closed membership event v1 schema retains its declared tuple and fence fields. +[JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to Account-authenticated recipient authority evidence, revocation-local admission decisions, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite recipient fence copied alongside the tuple, never a substitute for a tuple member. [Authentication](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence) owns the distinction between scope-wide source events and recipient evidence: maintaining Game Session's derived issuer projection uses exact Account-authenticated issuer source/checkpoint evidence and does not require an individual recipient binding. Account readback binds consumed source evidence to the recipient tuple and fence from one snapshot whenever the evidence is used for a recipient authority decision. The closed membership event v1 schema retains its declared tuple and fence fields. Revocation-local admission decisions, exact-binding leases, and gameplay bindings also carry the complete canonical `outboxCheckpoints` set: one exact `{outboxStreamKey, outboxSequence}` entry for every applicable scoped outbox stream. This set is admission freshness evidence, not a member of `authorityTuple` or a general JWT/registry claim, and any stream coordinates embedded in cutoff evidence must equal their corresponding set entries. @@ -128,7 +128,7 @@ Checking Account or Redis before every command gives a tighter revocation observ - Expose the applicable Account-owned authority tuple and complete committed `outboxCheckpoints` set through the admission decision, track every corresponding projection's application of its checkpoint, and fail closed before creating any new gameplay binding while any checkpoint is stale, gapped, ambiguous, or unconfirmed. - Implement the Account-owned exact-binding admission lease and monotonic `leaseFence` for new binding and reconnect/resume admission, bind the applicable complete `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, and complete `outboxCheckpoints` set into that lease, include the lease/fence, unchanged baseline, and checkpoint set in the atomic Game Session binding CAS, and keep the local record provisional until Account `COMMITTED` finalization. Prove cutoff-before-finalization rejects admission, finalization-before-cutoff admits only the then-current authority and is later revoked through the bounded event path, and any stale, ambiguous, expired, or uncertain lease state fails closed without leaving an admissible binding. - Implement Account-owned issuer, account, tenant, and membership authority-generation plus realm-grant-version projections with retry, set-if-greater, and cutoff-completion semantics. -- Prove canonical `eventDigest` recomputation over the complete event object, exact per-sequence duplicate-evidence retention and comparison keyed by `outboxStreamKey`, duplicate verification after local evidence eviction, first-event Account-snapshot bootstrap that atomically installs the per-stream `lastCommittedOutboxSequence` and bounded source evidence separately from any applicable Account-owned `lastCommittedTenantBillingSequence`, contiguous next-sequence enforcement for the source stream and independent billing sequence, and fail-closed reconciliation when retained or authoritative evidence is unavailable. For membership-scoped bootstrap, prove that the atomic install carries the unchanged `membershipBaseline`, same-snapshot membership state, and both independent membership projection high-waters with their matching checkpoint/source evidence; missing, divergent, or separately assembled values remain quarantined. +- Prove canonical `eventDigest` recomputation over the complete event object, exact per-sequence duplicate-evidence retention and comparison keyed by `outboxStreamKey`, duplicate verification after local evidence eviction, first-event Account-snapshot bootstrap that atomically installs the per-stream `lastCommittedOutboxSequence` and bounded source evidence separately from any applicable Account-owned `lastCommittedTenantBillingSequence`, contiguous next-sequence enforcement for the source stream and independent billing sequence, and fail-closed reconciliation when retained or authoritative evidence is unavailable. For issuer projection bootstrap, advancement, and duplicate verification, the authenticated checkpoint/source evidence must prove the exact issuer scope and complete applicable event identity, payload, and digest without requiring an individual recipient tuple, `issuanceFence`, or complete recipient checkpoint set; projection and matching source/checkpoint state are installed atomically. This projection cannot satisfy a recipient authority decision, which still requires the complete same-snapshot recipient binding. For membership-scoped bootstrap, prove that the atomic install carries the unchanged `membershipBaseline`, same-snapshot membership state, and both independent membership projection high-waters with their matching checkpoint/source evidence; missing, divergent, or separately assembled values remain quarantined. - Persist the authority versions required by active gameplay bindings and implement bounded issuer, account, tenant, caller-bound membership `{accountId, tenantId}`, and private-realm indexes for targeted termination, including bounded issuer and membership sweeps and the active-binding termination path. - Prove issuer- and membership-generation cutoff delivery, event projection, duplicate and gap handling, bounded issuer- and membership-index coverage, and termination of every affected active binding within the same fail-closed deadline as other authority cutoffs. - Add batched reconciliation, the 60-second freshness lease, event-gap repair, the index-unavailable fail-closed fallback, and bounded telemetry for event lag, projection failures, reconciliation age, and termination outcome. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 9a006dbecf..d37e9fd5be 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -16,7 +16,9 @@ Authentication applies the canonical `authorityTuple` unchanged to admission and Issuer-wide, account-wide, and tenant-wide publisher events use distinct closed, versioned source schemas. Each binds its exact source scope, committed generation and source version, stream checkpoint, event ID, and digest. Account commits the source mutation, scope advance, and outbox event atomically. These scope-wide source events are source evidence, not per-recipient Account authority snapshots, and do not carry a recipient-specific `issuanceFence` or complete recipient `authorityTuple`. -For each recipient, an Account-authenticated readback binds the consumed source event and checkpoint to that recipient's complete applicable `authorityTuple`, Account's actual `issuanceFence`, and complete `outboxCheckpoints` set in one Account snapshot. Consumers compare this complete binding when advancing, bootstrapping, retrying, or accepting duplicates. The Account readback composes source and recipient evidence without a distributed transaction or per-recipient event fanout. This distinction does not alter the closed `account-auth-authority-event/v1` membership event schema below, including its declared tuple and fence fields. +Game Session's derived issuer-generation projection bootstraps, advances, and verifies duplicates using Account-authenticated evidence for the exact issuer scope and source checkpoint. The evidence proves the exact issuer and stream identity, committed issuer generation and source version, sequence, and complete applicable source-event identity, payload, and digest. It does not require an individual recipient's `authorityTuple`, `issuanceFence`, or complete `outboxCheckpoints` set. An accepted bootstrap or next-sequence event atomically installs the projection watermark and matching source/checkpoint evidence. A conflicting, gapped, malformed, or ambiguous source/checkpoint is quarantined and fails closed; generation-only equality is not duplicate proof. This derived revocation projection grants no admission or rebind authority. + +When source evidence is used to authorize or update an individual recipient, an Account-authenticated readback binds the consumed source event and checkpoint to that recipient's complete applicable `authorityTuple`, Account's actual `issuanceFence`, and complete `outboxCheckpoints` set in one Account snapshot. Consumers compare this complete binding for recipient authorization, admission, binding, refresh, rebind, retry, and duplicate handling. The Account readback composes source and recipient evidence without a distributed transaction or per-recipient event fanout. This recipient evidence remains required for admission and rebind even when the issuer projection is current. This distinction does not alter the closed `account-auth-authority-event/v1` membership event schema below, including its declared tuple and fence fields. #### Account Password-Reset Source Event @@ -59,7 +61,7 @@ The following contract decisions are mandatory and resolve cross-document ambigu For the closed `account-auth-authority-event/v1` membership event, `membershipVersion` is the exact one-tenant map `{tenantId: version}` required by [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md), not a scalar field. Its sole key is the event's canonical `tenantId`; its value is a canonical positive decimal string from the same Account snapshot. The map is included unchanged in the canonical digest preimage, durable event, exact retry and readback comparisons, and consumer evidence. The decimal-string rule below applies to numeric values inside maps as well as standalone numeric fields. A consumer may extract a process-local scalar only after validating the complete map; no event producer or consumer transmits or persists that scalar as `membershipVersion`. - **Authority-generation writer** – The Account Service owns durable issuer, account, tenant, and `{accountId, tenantId}` membership authority generations and is the sole writer of every applicable canonical `authorityTuple` field, cutoff, and `issuanceFence`, plus their canonical `session:auth:generation:*` projections. Account commits the durable tuple/fence, applicable account-security or tenant-billing cutoff, and monotonic outbox event together; the projection is an asynchronous outbox output, not part of that atomic durable transaction. Consumers fail closed while the projection or its freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Other services must publish billing/security events and must not write canonical authority-generation state or projection keys; Game Session may write only its distinct derived issuer projection under the ADR 0022 schema. -- **Issuer projection checkpoint** – The Redis issuer-generation projections use `lastAppliedSourceOutboxSequence`, `lastAppliedSourceEventId`, and `lastAppliedSourceEventDigest` for the exact Account authority outbox stream. Sequence `0` is permitted only when that stream has no committed event; at that baseline, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, never serialized as `null`, an empty string, a zero digest, or another sentinel. For every positive sequence, both source-event fields are required non-null values in their canonical formats, and the projection advances only on the next contiguous sequence after exact checkpoint validation. These are projection-local replay/checkpoint fields, not JWT claims; JWT claims carry only the applicable authority tuple, including `issuerAuthGeneration`. +- **Issuer projection checkpoint** – The Redis issuer-generation projections use `lastAppliedSourceOutboxSequence`, `lastAppliedSourceEventId`, and `lastAppliedSourceEventDigest` for the exact Account authority outbox stream. Sequence `0` is permitted only when that stream has no committed event; at that baseline, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, never serialized as `null`, an empty string, a zero digest, or another sentinel. For every positive sequence, both source-event fields are required non-null values in their canonical formats, and the projection advances only on the next contiguous sequence after exact issuer-scope checkpoint validation. Bootstrap, advancement, and duplicate verification use the complete Account-authenticated issuer source/checkpoint evidence described above, not an individual recipient binding; matching generation alone is insufficient. Each accepted bootstrap or advancement atomically installs the projection and its corresponding source/checkpoint evidence. These are projection-local replay/checkpoint fields, not JWT claims; JWT claims carry only the applicable authority tuple, including `issuerAuthGeneration`. - **Authority outbox stream** – Account emits each revocation payload on exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound playtest grant scope produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep watermarks per exact stream key: duplicates with matching evidence at or below the watermark are no-ops, the next sequence is contiguous, a higher sequence is a gap only within that same key, and an unrelated scope never creates a gap. Conflicting duplicate evidence or a same-key gap stops affected validation/admission until Account reconciliation proves the exact checkpoint. - **Playtest grant stream identity** – The grant stream's scope, `sourceScope`, and `outboxStreamKey` are lifecycle-bound and must be produced and parsed only by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Any grant revision, tombstone, lookup, or admission evidence that omits `playtestLifecycleId` is incomplete and fails closed; a realm slug alone cannot select a grant. - **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; retained source evidence preserves each event's exact identity, digest, scope, and payload under its owning closed schema. When an event is used as recipient authority evidence, Account-authenticated readback separately binds its source checkpoint to the complete applicable `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one Account snapshot. A duplicate at or below the watermark is accepted only when its source evidence matches exactly and, where recipient authority applies, the complete Account binding also matches. If retained source evidence is unavailable, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)`; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed, while reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. 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 677c3c4140..7a02c609fe 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. Issuer-wide source-only projection evidence remains a distinct pending authority clarification and is not implemented by this Account-local producer. +The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. The accepted issuer-projection contract allows exact issuer-scoped source/checkpoint evidence for projection bootstrap, advancement, and duplicate verification; this Account-local password-reset producer does not implement the issuer projection or recipient readback required for admission and rebind. The gameplay Account-UUID carrier is published as [#2932](https://github.com/benhook1013/FireMUD/pull/2932), based on #2929 `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3`. Exact-head [CI 36933819297](https://github.com/benhook1013/FireMUD/actions/runs/36933819297) on `05313dc921aafe4b09b9c2b2649b2097bdc9892d` passed the full Account job and executed 124 listed strict Account cases without skips, failures or errors. Six early Game Session PostgreSQL gates executed 24 cases cleanly; its wider job was canceled after 15 Communication WebSocket cross-service failures, and TCP cross-service logged 13 failures with its database verifier skipped. TCP artifacts show successful LOGIN followed by PLAY denial: Game Session supplies its numeric catalog tenant key where the Account client requires a canonical tenant UUID, so the call fails before the RPC. Resolving the owner-backed UUID association and carrying it through the complete request/response predicates remains required work; no inferred mapping or relaxed guard is permitted. These are component proofs, not complete gameplay admission or transport proof. The independent whole-carrier review accepted and corrected two retained-Redis defects: unreadable presence is preserved by removal, re-registration and index pruning, and unreadable first-party context produces controlled invalid-context denial without persisted-context fallback. All 172 focused presence/LOGIN/PLAY unit cases executed with zero skips, failures or errors; formatting, Checkstyle, SpotBugs and documentation checks passed. Corrected-head CI, retained-Redis runtime and complete transport proof remain open. Game Logic/Social numeric sender/storage, Entity actor ownership, moderation consumers, complete Account authority and authenticated admission remain required owner work; no numeric aliases are inferred. Runtime activation, the membership RPC and Account ring mount remain denied. From d35058262b8b5657eeccd58c78487e5585bbf712 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:35:48 +1300 Subject: [PATCH 04/22] Require exact PostgreSQL password reset proof and retain its XML --- .github/workflows/ci.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4cf20a0a8..fc1ecea704 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1065,6 +1065,34 @@ jobs: fi echo "::endgroup::" + - name: 🔎 Verify Account password reset PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest \ + --require-suite net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest#commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest#exactRetryRecoversLostResponseWithoutAnySecondMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest#concurrentExactRetriesCommitOneSourceMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest#changedRetryConflictsAndConsecutiveResetsRequireExactPriorSourceProof()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest#appendAndReceiptReadbackFailuresRollBackEveryEarlierMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest#issuanceFenceOverflowRollsBackTokenPasswordAuthorityAndOutbox()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#concurrentPasswordResetAttemptsRecoverOneExactCommit()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#passwordResetRollbackPreservesEveryAtomicSourceComponent()' \ + account-service + + - name: 📤 Upload Account password reset PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-password-reset-postgresql-proof-${{ github.sha }} + path: | + services/account-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: 🔎 Verify Account PostgreSQL proof cases if: ${{ matrix.module == 'account-service' }} run: | From 0ff7ccc6b20bcfef82dd86e63138f04631b1aea6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:37:05 +1300 Subject: [PATCH 05/22] Record retained tenant UUID composed proof and remaining activation gates --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7a02c609fe..4522452d42 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The retained Game Session tenant-UUID consumer candidate normally incorporates Account password-reset source #2933 `933dde7f6951fd040c26864acdb6165f7726a43d`. `PLAY` resolves only the exact workload-namespace/private-key association from an immutable owner-approved receipt, cross-reads its operation, request, canonical UUID and retained key, then uses that UUID in Account entitlement, membership and realm-grant requests and response comparisons. Missing configuration, missing association, nil or contradictory evidence denies without importer, roster or admission mutation. The full composed Account/Common Platform/Game Session checks, both service JARs, formatting/static analysis, links and Markdown passed166tasks(55executed/25from-cache/86up-to-date). Game Session newly executed1,806unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/137integration/33cross-service cases skipped. Its eleven retained-association PostgreSQL cases, including the two new lookup cases, compiled but skipped without Docker. Account526unit/167skipped PostgreSQL and Common Platform133unit results were reused from cache, not newly executed in this composed run. Normal ancestry preserves the complete Account/Common Platform parent subtree and all original Game Session candidate hunks byte-for-byte. This corrects the numeric tenant request boundary, not audited importer/source registration, fresh runtime catalog enrollment, complete typed entitlement/grant evidence, UUID-aware Game Logic/Social/moderation consumers, authenticated positive transport proof or runtime activation. The membership RPC, credential paths and Account ring mount remain denied. + The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. The accepted issuer-projection contract allows exact issuer-scoped source/checkpoint evidence for projection bootstrap, advancement, and duplicate verification; this Account-local password-reset producer does not implement the issuer projection or recipient readback required for admission and rebind. The gameplay Account-UUID carrier is published as [#2932](https://github.com/benhook1013/FireMUD/pull/2932), based on #2929 `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3`. Exact-head [CI 36933819297](https://github.com/benhook1013/FireMUD/actions/runs/36933819297) on `05313dc921aafe4b09b9c2b2649b2097bdc9892d` passed the full Account job and executed 124 listed strict Account cases without skips, failures or errors. Six early Game Session PostgreSQL gates executed 24 cases cleanly; its wider job was canceled after 15 Communication WebSocket cross-service failures, and TCP cross-service logged 13 failures with its database verifier skipped. TCP artifacts show successful LOGIN followed by PLAY denial: Game Session supplies its numeric catalog tenant key where the Account client requires a canonical tenant UUID, so the call fails before the RPC. Resolving the owner-backed UUID association and carrying it through the complete request/response predicates remains required work; no inferred mapping or relaxed guard is permitted. These are component proofs, not complete gameplay admission or transport proof. The independent whole-carrier review accepted and corrected two retained-Redis defects: unreadable presence is preserved by removal, re-registration and index pruning, and unreadable first-party context produces controlled invalid-context denial without persisted-context fallback. All 172 focused presence/LOGIN/PLAY unit cases executed with zero skips, failures or errors; formatting, Checkstyle, SpotBugs and documentation checks passed. Corrected-head CI, retained-Redis runtime and complete transport proof remain open. Game Logic/Social numeric sender/storage, Entity actor ownership, moderation consumers, complete Account authority and authenticated admission remain required owner work; no numeric aliases are inferred. Runtime activation, the membership RPC and Account ring mount remain denied. From aa22f67be628748205414b954041cd003570d84b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:37:15 +1300 Subject: [PATCH 06/22] Align target logout profiles with the canonical route matrix --- .../microservices/account-service/api-contracts.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 165a9cdb4a..1c1925f5c7 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -256,7 +256,8 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | | Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | -| Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | +| Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | +| Target account logout | `/auth/logout`, `/auth/logout-all` | Exact authenticated account scope through either `control-ui` or `player-bootstrap`, as declared by the [Authorization Route Matrix](../../system-architecture-authz-route-matrix.md) | Both routes remain target-only and unroutable. They follow the matrix's combined logout profile and bounded durable lifecycle-only retry exception; registry absence does not authorize a retry or create reusable authorization context. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | | Security-locked export recovery | `/accounts/{accountId}/exports/**` while the account is `security_locked` | Account-issued `security-lock-export` credential from the Account-owned recovery workflow; no ordinary JWT, pending-deletion credential, or support-only access | Exact global account subject and export-job binding, no tenant selector, single-use initiation and expiring status/content authorization. The credential authorizes only this export lifecycle and cannot restore login, cancel deletion, mutate billing, or enter gameplay. | | Pending-deletion access | `/accounts/{accountId}/deletion`, `/accounts/{accountId}/deletion/cancel`, `/accounts/{accountId}/exports/**`, `/accounts/{accountId}/deletion/billing-settlement` | Opaque `pending-deletion-access` credential through the Account-owned workflow registry | Target-only exact `pending_deletion_scoped` route classification for deletion-specific routes and the canonical asynchronous export lifecycle. Once the account enters pending deletion, this row takes precedence over ordinary control-plane classification: `control-ui` authority is revoked and cannot access export or any other pending-deletion route. | From 194eae43c6d10b2f5d476d7a65baae4ee3e44bc3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:40:20 +1300 Subject: [PATCH 07/22] Require retained tenant UUID PostgreSQL readback and record final parent --- .github/workflows/ci.yml | 11 +++++++++++ .../player-access-and-session.md | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc1ecea704..024cb56a6b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -987,8 +987,19 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#rollbackLeavesNoAssociationClaimAndNewAttemptSucceeds()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnSameImmutableReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupReturnsHistoricalUuidOnlyForExactNamespaceAndKey()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows()' \ game-session-service + - name: Upload Game Session retained tenant UUID PostgreSQL proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-retained-tenant-uuid-postgresql-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session management owner UUID PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | 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 4522452d42..281df34707 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The retained Game Session tenant-UUID consumer candidate normally incorporates Account password-reset source #2933 `933dde7f6951fd040c26864acdb6165f7726a43d`. `PLAY` resolves only the exact workload-namespace/private-key association from an immutable owner-approved receipt, cross-reads its operation, request, canonical UUID and retained key, then uses that UUID in Account entitlement, membership and realm-grant requests and response comparisons. Missing configuration, missing association, nil or contradictory evidence denies without importer, roster or admission mutation. The full composed Account/Common Platform/Game Session checks, both service JARs, formatting/static analysis, links and Markdown passed166tasks(55executed/25from-cache/86up-to-date). Game Session newly executed1,806unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/137integration/33cross-service cases skipped. Its eleven retained-association PostgreSQL cases, including the two new lookup cases, compiled but skipped without Docker. Account526unit/167skipped PostgreSQL and Common Platform133unit results were reused from cache, not newly executed in this composed run. Normal ancestry preserves the complete Account/Common Platform parent subtree and all original Game Session candidate hunks byte-for-byte. This corrects the numeric tenant request boundary, not audited importer/source registration, fresh runtime catalog enrollment, complete typed entitlement/grant evidence, UUID-aware Game Logic/Social/moderation consumers, authenticated positive transport proof or runtime activation. The membership RPC, credential paths and Account ring mount remain denied. +The retained Game Session tenant-UUID consumer candidate normally incorporates Account password-reset source #2933 `aa22f67be628748205414b954041cd003570d84b`. `PLAY` resolves only the exact workload-namespace/private-key association from an immutable owner-approved receipt, cross-reads its operation, request, canonical UUID and retained key, then uses that UUID in Account entitlement, membership and realm-grant requests and response comparisons. Missing configuration, missing association, nil or contradictory evidence denies without importer, roster or admission mutation. The full composed Account/Common Platform/Game Session checks, both service JARs, formatting/static analysis, links and Markdown passed166tasks(55executed/25from-cache/86up-to-date). Game Session newly executed1,806unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/137integration/33cross-service cases skipped. Its eleven retained-association PostgreSQL cases, including the two new lookup cases, compiled but skipped without Docker. Account526unit/167skipped PostgreSQL and Common Platform133unit results were reused from cache, not newly executed in this composed run. Normal ancestry preserves the complete Account/Common Platform parent subtree and all original Game Session candidate hunks byte-for-byte. This corrects the numeric tenant request boundary, not audited importer/source registration, fresh runtime catalog enrollment, complete typed entitlement/grant evidence, UUID-aware Game Logic/Social/moderation consumers, authenticated positive transport proof or runtime activation. The membership RPC, credential paths and Account ring mount remain denied. The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. The accepted issuer-projection contract allows exact issuer-scoped source/checkpoint evidence for projection bootstrap, advancement, and duplicate verification; this Account-local password-reset producer does not implement the issuer projection or recipient readback required for admission and rebind. From 0a3f22758acb47b482813698a035cf2085187615 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:15:19 +1300 Subject: [PATCH 08/22] Prove exact committed retained-tenant association readback --- .github/workflows/ci.yml | 6 +- design/project-management/ai-observations.md | 9 + .../player-access-and-session.md | 4 + ...ssionRetainedTenantAssociationService.java | 46 ++- ...tAssociationRepositoryIntegrationTest.java | 237 ++++++++++++++ ...nRetainedTenantAssociationServiceTest.java | 298 +++++++++++++++++- 6 files changed, 595 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 024cb56a6b..a45453b78f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -989,6 +989,8 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnSameImmutableReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupReturnsHistoricalUuidOnlyForExactNamespaceAndKey()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#serviceReturnsExactCommittedAssociationAfterOwnerTransaction()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#serviceRecoversPostCommitReadFailureWithoutRewritingHistoricalAssociation()' \ game-session-service - name: Upload Game Session retained tenant UUID PostgreSQL proof results @@ -996,7 +998,7 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: game-session-retained-tenant-uuid-postgresql-proof-${{ github.sha }} - path: services/game-session-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest.xml + path: services/game-session-service/build/test-results/integrationTest/TEST-*GameSessionRetainedTenantAssociationRepositoryIntegrationTest.xml if-no-files-found: warn retention-days: 7 @@ -1099,7 +1101,7 @@ jobs: with: name: account-password-reset-postgresql-proof-${{ github.sha }} path: | - services/account-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*PasswordResetAuthorityProducerPostgresIntegrationTest.xml services/account-service/build/test-results/integrationTest/TEST-net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.xml if-no-files-found: warn retention-days: 7 diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f526f9be7a..674ff30c18 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -216,3 +216,12 @@ Entry format: - `2026-10-02`: Do not use a truncated PR file array as the changed-file count - Context: `gh pr view --json files` returned 100 entries for the coherent Unit 1B carrier, while the GitHub `changedFiles` scalar and the exact local base/head diff both reported 116. Counting the returned array alone would have understated the published scope. - Expected pattern: use the PR's `changedFiles` scalar for scope counts and independently compare the exact base/head diff; when individual paths are needed, retrieve the complete paginated list rather than treating a capped array as full coverage. A truncated array is not evidence that the patch fits a reviewer ceiling. + +- `2026-10-02`: Keep prerequisite proof stages inside coherent review packages + - Context: the Account source stage and retained Game Session tenant-UUID consumer were published as separate 21- and 16-file PRs, but their combined patch was only 35 unique files. Human direction favors related packages of roughly 60–80 files when suitable, without padding or weakening independently named proof and activation limits. + - Outcome: #2933 absorbed #2935 by advancing to its identical published head, preserving every hunk and history. GitHub then marked the child merged because its base contained that exact head; no PR merge or auto-merge action was executed. Exact-head CI remains attributable to the unchanged tree. + - Expected pattern: separate contracts and proof in the PR handoff rather than creating a PR per helper or test stage. Check actual unique paths and complete-tree preservation, publish the combined boundary, then read back both GitHub state and the configured queue; do not infer deployment or readiness from a child's merged label. + +- `2026-10-02`: Match long Gradle report filenames separately from JUnit suite identities + - Context: exact CI36947366507 strictly proved the eight reset cases and eleven retained-association cases, but artifact paths using the literal suite name missed the producer and retained-association XML. The actual producer filename was `TEST-integ-LL300RMKP9ANC.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest.xml`, while its XML retained the canonical full suite name. + - Expected pattern: use class-bounded filename globs for artifact capture and retain exact canonical suite/case identities in the strict verifier. Prove the glob matches the actual reports; an upload success with one file is not evidence that every intended suite was retained. Keep execution-log proof distinct from missing raw XML and require a subsequent runner outcome for the corrected capture path. 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 281df34707..bdec90b5d4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The current combined [#2933](https://github.com/benhook1013/FireMUD/pull/2933) absorbs the retained tenant-UUID consumer formerly packaged as #2935; separate Account-source and Game Session-consumer proof remains attributed below. Exact-head [CI 36947366507](https://github.com/benhook1013/FireMUD/actions/runs/36947366507) at `194eae43c6d10b2f5d476d7a65baae4ee3e44bc3` strictly executed all six password-reset producer and both required application cases once without skips, failures or errors. Game Session's component step executed four snapshot and eleven association cases cleanly, including both retained-key UUID lookup methods. These counts are strict job-log evidence: the Account artifact retained only the application XML, and the Game Session artifact missed its long XML filename. Class-bounded artifact globs correct that capture defect without changing suite/case requirements. The aggregate run failed, and the later broad Game Session task was canceled after cross-service assertions; full transport/admission proof remains open, not presumed inherited or fixed by these successful components. + +The unwired retained-association service now performs exact committed-outcome readback after its owner transaction, comparing the complete immutable receipt rather than reporting the transaction-local result alone. An unavailable or contradictory read cannot authorize success or trigger repair; retry retains the original request and historical association. Its affected full Game Session check and JAR passed with formatting, Checkstyle, SpotBugs and JaCoCo: 123 tasks, 35 executed and 88 up-to-date. Game Session executed 1,813 unit cases, including all thirteen service cases, eighteen non-PostgreSQL integration cases and one cross-service case without failures/errors; seventeen unit, 139 integration and 33 cross-service cases skipped. All thirteen association PostgreSQL cases compiled but skipped without local Docker, including the two new service composition cases. The earlier exact-head component proof does not attest those two new cases. Audited source registration/import invocation, approval custody and live authenticated receiver proof remain open, with membership, credentials, catalog activation and the Account ring mount denied. + The retained Game Session tenant-UUID consumer candidate normally incorporates Account password-reset source #2933 `aa22f67be628748205414b954041cd003570d84b`. `PLAY` resolves only the exact workload-namespace/private-key association from an immutable owner-approved receipt, cross-reads its operation, request, canonical UUID and retained key, then uses that UUID in Account entitlement, membership and realm-grant requests and response comparisons. Missing configuration, missing association, nil or contradictory evidence denies without importer, roster or admission mutation. The full composed Account/Common Platform/Game Session checks, both service JARs, formatting/static analysis, links and Markdown passed166tasks(55executed/25from-cache/86up-to-date). Game Session newly executed1,806unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/137integration/33cross-service cases skipped. Its eleven retained-association PostgreSQL cases, including the two new lookup cases, compiled but skipped without Docker. Account526unit/167skipped PostgreSQL and Common Platform133unit results were reused from cache, not newly executed in this composed run. Normal ancestry preserves the complete Account/Common Platform parent subtree and all original Game Session candidate hunks byte-for-byte. This corrects the numeric tenant request boundary, not audited importer/source registration, fresh runtime catalog enrollment, complete typed entitlement/grant evidence, UUID-aware Game Logic/Social/moderation consumers, authenticated positive transport proof or runtime activation. The membership RPC, credential paths and Account ring mount remain denied. The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. The accepted issuer-projection contract allows exact issuer-scoped source/checkpoint evidence for projection bootstrap, advancement, and duplicate verification; this Account-local password-reset producer does not implement the issuer projection or recipient readback required for admission and rebind. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java index ded5ce90df..e30cd2eef0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Base64; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; @@ -83,7 +84,50 @@ public AssociationReceipt associate( LegacyGameSessionTenantAssociationReceipt validatedReceipt = validateOwnerReceipt(ownerReceipt, tenantUuid, approvalOperationUuid, legacyKey); - return ownerTransaction.execute(status -> repository.register(requestUuid, validatedReceipt)); + AssociationReceipt registeredReceipt = + ownerTransaction.execute(status -> repository.register(requestUuid, validatedReceipt)); + requireRegistrationMatches( + registeredReceipt, requestUuid, validatedReceipt, approvalOperationUuid); + + Optional committedReadback = + repository.read( + registeredReceipt.operationId(), + requestUuid, + tenantUuid, + Long.parseLong(legacyKey), + workloadNamespace); + if (committedReadback == null || committedReadback.isEmpty()) { + throw new IllegalStateException("Committed retained-tenant association readback is missing"); + } + AssociationReceipt committedReceipt = committedReadback.orElseThrow(); + if (!registeredReceipt.equals(committedReceipt)) { + throw new IllegalStateException( + "Committed retained-tenant association readback contradicts its registration receipt"); + } + return committedReceipt; + } + + private static void requireRegistrationMatches( + AssociationReceipt receipt, + UUID associationRequestId, + LegacyGameSessionTenantAssociationReceipt ownerReceipt, + UUID approvalOperationId) { + if (receipt == null) { + throw new IllegalStateException( + "Committed retained-tenant association registration receipt is missing"); + } + GameSessionTenantAssociationEvidence ownerEvidence = ownerReceipt.evidence(); + if (receipt.operationId() == null + || NIL_UUID.equals(receipt.operationId()) + || !associationRequestId.equals(receipt.associationRequestId()) + || !Objects.equals(ownerEvidence, receipt.approval()) + || !Objects.equals(ownerReceipt.manifestDigest(), receipt.approvalManifestDigest()) + || !Objects.equals(ownerReceipt.ed25519Signature(), receipt.approvalSignature()) + || !approvalOperationId.equals(ownerEvidence.operationId())) { + throw new IllegalStateException( + "Committed retained-tenant association registration contradicts its exact request" + + " or approval"); + } } private LegacyGameSessionTenantAssociationReceipt validateOwnerReceipt( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index d9c7b1a3ec..fcc6165c83 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -3,10 +3,14 @@ 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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; 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.verifyNoInteractions; import java.io.ByteArrayOutputStream; @@ -25,7 +29,10 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationConflictException; @@ -33,6 +40,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.InvalidAssociationEvidenceException; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import net.firedevops.firemud.gamesession.service.GameSessionRetainedTenantAssociationService; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; @@ -44,6 +52,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -179,6 +188,228 @@ void retainedKeyLookupReturnsHistoricalUuidOnlyForExactNamespaceAndKey() { assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); } + @Test + void serviceReturnsExactCommittedAssociationAfterOwnerTransaction() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-before-service-association"); + UUID associationRequestId = uuid(1101); + UUID approvalOperationId = uuid(1102); + UUID canonicalTenantId = uuid(1103); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(approvalOperationId, canonicalTenantId, 42L, fixture.capture(42L)); + + // The transport is mocked; this verifies database composition, not live mTLS. + GameDesignRuntimeTenantIdentityClient sourceClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + AtomicReference ownerReadRequestId = new AtomicReference<>(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + ownerReadRequestId.set(invocation.getArgument(3, String.class)); + return approval; + }) + .when(sourceClient) + .resolveLegacyGameSessionTenantAssociation( + eq(canonicalTenantId.toString()), + eq(approvalOperationId.toString()), + eq("42"), + anyString()); + + GameSessionRetainedTenantAssociationRepository committedReadRepository = + spy(fixture.repository); + AtomicReference committedLocalOperationId = new AtomicReference<>(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + committedLocalOperationId.set(invocation.getArgument(0, UUID.class)); + return invocation.callRealMethod(); + }) + .when(committedReadRepository) + .read( + any(UUID.class), + eq(associationRequestId), + eq(canonicalTenantId), + eq(42L), + eq(NAMESPACE)); + GameSessionRetainedTenantAssociationService service = + new GameSessionRetainedTenantAssociationService( + sourceClient, + committedReadRepository, + Objects.requireNonNull(fixture.transactions.getTransactionManager()), + NAMESPACE); + + AssociationReceipt receipt = + service.associate( + associationRequestId.toString(), + canonicalTenantId.toString(), + approvalOperationId.toString(), + "42"); + + assertThat(ownerReadRequestId.get()).isNotBlank(); + assertThat(UUID.fromString(ownerReadRequestId.get()).toString()) + .isEqualTo(ownerReadRequestId.get()); + assertThat(ownerReadRequestId.get()) + .isNotEqualTo(associationRequestId.toString()) + .isNotEqualTo(approvalOperationId.toString()); + assertThat(receipt.operationId()).isEqualTo(committedLocalOperationId.get()); + assertThat(receipt.operationId()) + .isNotEqualTo(approvalOperationId) + .isNotEqualTo(associationRequestId); + verify(sourceClient) + .resolveLegacyGameSessionTenantAssociation( + canonicalTenantId.toString(), + approvalOperationId.toString(), + "42", + ownerReadRequestId.get()); + verify(committedReadRepository) + .read(receipt.operationId(), associationRequestId, canonicalTenantId, 42L, NAMESPACE); + assertThat(receipt) + .isEqualTo( + committedReadRepository + .read( + receipt.operationId(), associationRequestId, canonicalTenantId, 42L, NAMESPACE) + .orElseThrow()); + assertThat(committedReadRepository.readCanonicalTenantIdByRetainedTenantKey(42L, NAMESPACE)) + .contains(canonicalTenantId); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void serviceRecoversPostCommitReadFailureWithoutRewritingHistoricalAssociation() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-before-post-commit-read-failure"); + UUID associationRequestId = uuid(1201); + UUID approvalOperationId = uuid(1202); + UUID canonicalTenantId = uuid(1203); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(approvalOperationId, canonicalTenantId, 42L, fixture.capture(42L)); + String sourceXminBefore = fixture.instanceXmin(420L); + + // The transport is mocked; this verifies database composition, not live mTLS. + GameDesignRuntimeTenantIdentityClient sourceClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return approval; + }) + .when(sourceClient) + .resolveLegacyGameSessionTenantAssociation( + eq(canonicalTenantId.toString()), + eq(approvalOperationId.toString()), + eq("42"), + anyString()); + + GameSessionRetainedTenantSnapshotRepository snapshotRepository = + spy(fixture.snapshotRepository); + GameSessionRetainedTenantAssociationRepository serviceRepository = + spy( + new GameSessionRetainedTenantAssociationRepository( + fixture.dsl, snapshotRepository, NAMESPACE)); + AtomicBoolean failFirstPostCommitRead = new AtomicBoolean(true); + AtomicReference postCommitReadOperationId = new AtomicReference<>(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + postCommitReadOperationId.set(invocation.getArgument(0, UUID.class)); + if (failFirstPostCommitRead.compareAndSet(true, false)) { + throw new IllegalStateException("simulated post-commit read outage"); + } + return invocation.callRealMethod(); + }) + .when(serviceRepository) + .read( + any(UUID.class), + eq(associationRequestId), + eq(canonicalTenantId), + eq(42L), + eq(NAMESPACE)); + GameSessionRetainedTenantAssociationService service = + new GameSessionRetainedTenantAssociationService( + sourceClient, + serviceRepository, + Objects.requireNonNull(fixture.transactions.getTransactionManager()), + NAMESPACE); + + assertThatThrownBy( + () -> + service.associate( + associationRequestId.toString(), + canonicalTenantId.toString(), + approvalOperationId.toString(), + "42")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulated post-commit read outage"); + assertThat(failFirstPostCommitRead.get()).isFalse(); + assertThat(fixture.instanceRuntimeVersion(420L)) + .isEqualTo("runtime-before-post-commit-read-failure"); + assertThat(fixture.instanceXmin(420L)).isEqualTo(sourceXminBefore); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.storedRequestCount(associationRequestId)).isEqualTo(1L); + UUID localOperationId = + fixture.storedByRequest(associationRequestId).get("operation_id", UUID.class); + assertThat(localOperationId) + .isNotNull() + .isNotEqualTo(approvalOperationId) + .isNotEqualTo(associationRequestId); + assertThat(postCommitReadOperationId.get()).isEqualTo(localOperationId); + + AssociationReceipt historicalReceipt = + fixture + .repository + .read(localOperationId, associationRequestId, canonicalTenantId, 42L, NAMESPACE) + .orElseThrow(); + String associationXmin = fixture.associationXmin(associationRequestId); + assertThat(historicalReceipt.approval()).isEqualTo(approval.evidence()); + assertThat(historicalReceipt.snapshot().evidenceDigest()) + .isEqualTo(approval.evidence().gameSessionEvidenceDigest()); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-post-commit-read-failure", + 420L); + assertThat(fixture.instanceRuntimeVersion(420L)) + .isEqualTo("runtime-after-post-commit-read-failure"); + assertThat(fixture.capture(42L).evidenceDigest()) + .isNotEqualTo(historicalReceipt.snapshot().evidenceDigest()); + + AssociationReceipt recovered = + service.associate( + associationRequestId.toString(), + canonicalTenantId.toString(), + approvalOperationId.toString(), + "42"); + + assertThat(postCommitReadOperationId.get()).isEqualTo(localOperationId); + verify(serviceRepository, times(2)) + .read(localOperationId, associationRequestId, canonicalTenantId, 42L, NAMESPACE); + assertThat(recovered).isEqualTo(historicalReceipt); + assertThat(recovered.operationId()).isEqualTo(localOperationId); + assertThat(recovered.operationId()).isEqualTo(historicalReceipt.operationId()); + assertThat(recovered.associationRequestId()).isEqualTo(associationRequestId); + assertThat(recovered.requestDigest()).isEqualTo(historicalReceipt.requestDigest()); + assertThat(recovered.approvalManifestDigest()) + .isEqualTo(historicalReceipt.approvalManifestDigest()); + assertThat(recovered.snapshot()).isEqualTo(historicalReceipt.snapshot()); + assertThat(recovered.snapshot().evidenceDigest()) + .isEqualTo(historicalReceipt.snapshot().evidenceDigest()); + assertThat(recovered.receiptDigest()).isEqualTo(historicalReceipt.receiptDigest()); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.storedRequestCount(associationRequestId)).isEqualTo(1L); + assertThat(fixture.associationXmin(associationRequestId)).isEqualTo(associationXmin); + verify(snapshotRepository, times(1)).capture(NAMESPACE, "42"); + verify(sourceClient, times(2)) + .resolveLegacyGameSessionTenantAssociation( + eq(canonicalTenantId.toString()), + eq(approvalOperationId.toString()), + eq("42"), + anyString()); + assertThat( + fixture.repository.read( + localOperationId, associationRequestId, canonicalTenantId, 42L, NAMESPACE)) + .contains(historicalReceipt); + } + @Test void retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows() { Fixture malformedFixture = fixture(); @@ -707,5 +938,11 @@ String instanceXmin(long instanceId) { dsl.fetchOne("SELECT xmin::text AS xmin FROM game_instances WHERE id = ?", instanceId); return Objects.requireNonNull(row).get("xmin", String.class); } + + String instanceRuntimeVersion(long instanceId) { + Record row = + dsl.fetchOne("SELECT runtime_version FROM game_instances WHERE id = ?", instanceId); + return Objects.requireNonNull(row).get("runtime_version", String.class); + } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java index 746e3c07de..790fe086f1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java @@ -3,24 +3,33 @@ 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.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Base64; +import java.util.HexFormat; import java.util.List; import java.util.Locale; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; import net.firedevops.firemud.gamesession.service.GameSessionRetainedTenantAssociationService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -40,8 +49,15 @@ class GameSessionRetainedTenantAssociationServiceTest { private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID APPROVAL_OPERATION = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID LOCAL_OPERATION = + UUID.fromString("77777777-7777-4777-8777-777777777777"); private static final UUID OTHER_TENANT = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final String LEGACY_KEY = "42"; + private static final String SNAPSHOT_DOMAIN = "game-session/retained-tenant-identity-snapshot/v2"; + private static final String ASSOCIATION_REQUEST_DOMAIN = + "game-session/retained-tenant-association-request/v1"; + private static final String ASSOCIATION_RECEIPT_DOMAIN = + "game-session/retained-tenant-association-receipt/v1"; private final GameDesignRuntimeTenantIdentityClient client = mock(GameDesignRuntimeTenantIdentityClient.class); @@ -61,13 +77,15 @@ void clearTransactionState() { @Test void authenticatesOwnerReceiptBeforeStartingReadCommittedRequiresNewTransaction() { LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); - AssociationReceipt localReceipt = mock(AssociationReceipt.class); + AssociationReceipt localReceipt = associationReceipt(REQUEST, LOCAL_OPERATION, ownerReceipt); when(client.resolveLegacyGameSessionTenantAssociation( eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) .thenReturn(ownerReceipt); when(transactionManager.getTransaction(any(TransactionDefinition.class))) .thenReturn(new SimpleTransactionStatus()); when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt); + when(repository.read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE)) + .thenReturn(Optional.of(localReceipt)); assertThat( service.associate( @@ -84,6 +102,7 @@ void authenticatesOwnerReceiptBeforeStartingReadCommittedRequiresNewTransaction( ordered.verify(transactionManager).getTransaction(definition.capture()); ordered.verify(repository).register(REQUEST, ownerReceipt); ordered.verify(transactionManager).commit(any(TransactionStatus.class)); + ordered.verify(repository).read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE); assertThat(definition.getValue().getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertThat(definition.getValue().getIsolationLevel()) @@ -101,6 +120,208 @@ void authenticatesOwnerReceiptBeforeStartingReadCommittedRequiresNewTransaction( assertThat(readRequestId).isNotEqualTo(REQUEST).isNotEqualTo(APPROVAL_OPERATION); } + @Test + void commitFailureDoesNotStartCommittedOutcomeRead() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + AssociationReceipt localReceipt = associationReceipt(REQUEST, LOCAL_OPERATION, ownerReceipt); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt); + doThrow(new IllegalStateException("commit failed")) + .when(transactionManager) + .commit(any(TransactionStatus.class)); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("commit failed"); + + verify(transactionManager).commit(any(TransactionStatus.class)); + verify(repository, never()) + .read(any(UUID.class), any(UUID.class), any(UUID.class), anyLong(), anyString()); + } + + @Test + void nullRegistrationReceiptFailsAfterCommitWithoutRead() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(null); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("registration receipt is missing"); + + verify(transactionManager).commit(any(TransactionStatus.class)); + verify(repository, never()) + .read(any(UUID.class), any(UUID.class), any(UUID.class), anyLong(), anyString()); + } + + @Test + void missingOwnerReceiptFailsBeforeTransactionOrLocalRead() { + when(client.resolveLegacyGameSessionTenantAssociation( + anyString(), anyString(), anyString(), anyString())) + .thenReturn(null); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("approval receipt is missing"); + + verifyNoInteractions(transactionManager, repository); + } + + @Test + void missingCommittedReadbackFailsAfterSuccessfulRegistration() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + AssociationReceipt localReceipt = associationReceipt(REQUEST, LOCAL_OPERATION, ownerReceipt); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt); + when(repository.read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE)) + .thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is missing"); + + verify(transactionManager).commit(any(TransactionStatus.class)); + verify(repository).read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE); + } + + @Test + void contradictoryRegistrationTupleFailsAfterCommitWithoutRead() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + LegacyGameSessionTenantAssociationReceipt contradictoryOwnerReceipt = + receipt(NAMESPACE, OTHER_TENANT, 42L); + AssociationReceipt contradictoryRegistration = + associationReceipt(REQUEST, LOCAL_OPERATION, contradictoryOwnerReceipt); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(contradictoryRegistration); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("registration contradicts its exact request or approval"); + + verify(transactionManager).commit(any(TransactionStatus.class)); + verify(repository, never()) + .read(any(UUID.class), any(UUID.class), any(UUID.class), anyLong(), anyString()); + } + + @Test + void contradictoryCommittedReceiptFailsFullImmutableEqualityCheck() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + AssociationReceipt localReceipt = associationReceipt(REQUEST, LOCAL_OPERATION, ownerReceipt); + AssociationReceipt contradictoryReadback = + new AssociationReceipt( + localReceipt.operationId(), + localReceipt.associationRequestId(), + localReceipt.requestDigest(), + localReceipt.approval(), + localReceipt.approvalManifestDigest(), + localReceipt.approvalSignature(), + localReceipt.snapshot(), + framedDigest("contradictory-receipt-digest")); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt); + when(repository.read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE)) + .thenReturn(Optional.of(contradictoryReadback)); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback contradicts its registration receipt"); + + verify(transactionManager).commit(any(TransactionStatus.class)); + verify(repository).read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE); + } + + @Test + void unavailableReadCanRecoverThroughExactSameRequestRetry() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + AssociationReceipt localReceipt = associationReceipt(REQUEST, LOCAL_OPERATION, ownerReceipt); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt, ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus(), new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt, localReceipt); + when(repository.read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE)) + .thenThrow(new IllegalStateException("post-commit read unavailable")) + .thenReturn(Optional.of(localReceipt)); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("post-commit read unavailable"); + + assertThat( + service.associate( + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), LEGACY_KEY)) + .isSameAs(localReceipt); + + verify(client, times(2)) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString()); + verify(repository, times(2)).register(REQUEST, ownerReceipt); + verify(repository, times(2)).read(LOCAL_OPERATION, REQUEST, TENANT, 42L, NAMESPACE); + } + @Test void rejectsMalformedCallerBindingBeforeOwnerReadOrTransaction() { List malformed = @@ -238,6 +459,8 @@ private static LegacyGameSessionTenantAssociationReceipt receipt( private static LegacyGameSessionTenantAssociationReceipt receipt( String namespace, UUID operationId, UUID canonicalTenantId, long legacyKey) { + GameSessionRetainedTenantSnapshot snapshot = + retainedSnapshot(namespace, Long.toString(legacyKey)); GameSessionTenantAssociationEvidence evidence = new GameSessionTenantAssociationEvidence( 1, @@ -252,9 +475,80 @@ private static LegacyGameSessionTenantAssociationReceipt receipt( "501", "source-game-501", "RETAINED_GAME_V30", - "sha256:" + "a".repeat(64)); + snapshot.evidenceDigest()); String signature = Base64.getEncoder().encodeToString(new byte[64]); return new LegacyGameSessionTenantAssociationReceipt( evidence, evidence.manifestDigest(), signature); } + + private static AssociationReceipt associationReceipt( + UUID associationRequestId, + UUID localOperationId, + LegacyGameSessionTenantAssociationReceipt ownerReceipt) { + GameSessionTenantAssociationEvidence evidence = ownerReceipt.evidence(); + GameSessionRetainedTenantSnapshot snapshot = + retainedSnapshot(evidence.targetNamespace(), evidence.legacyGameSessionTenantId()); + String requestDigest = + framedDigest( + ASSOCIATION_REQUEST_DOMAIN, + evidence.targetNamespace(), + associationRequestId.toString(), + ownerReceipt.manifestDigest(), + ownerReceipt.ed25519Signature()); + String receiptDigest = + framedDigest( + ASSOCIATION_RECEIPT_DOMAIN, + localOperationId.toString(), + requestDigest, + ownerReceipt.manifestDigest(), + snapshot.evidenceDigest()); + return new AssociationReceipt( + localOperationId, + associationRequestId, + requestDigest, + evidence, + ownerReceipt.manifestDigest(), + ownerReceipt.ed25519Signature(), + snapshot, + receiptDigest); + } + + private static GameSessionRetainedTenantSnapshot retainedSnapshot( + String namespace, String legacyKey) { + String canonicalJson = + "{\"backfillIssues\":[],\"instances\":[{\"game_template_id\":null," + + "\"generation_config_revision\":null,\"id\":\"1\"," + + "\"launch_descriptor_id\":null,\"owner_account_id\":\"7\"," + + "\"owner_account_uuid\":null,\"release_bundle_id\":null," + + "\"remap_set_id\":null,\"row_version\":\"1\"," + + "\"runtime_version\":\"retained-v30\"," + + "\"script_patch_pinned_control_plane_request_id\":null," + + "\"script_patch_version\":null,\"script_pin_epoch\":null," + + "\"status\":\"STOPPED\",\"tenant_id\":\"" + + legacyKey + + "\",\"version_id\":null,\"version_state_epoch\":null}]," + + "\"legacyGameSessionTenantId\":\"" + + legacyKey + + "\",\"pointerEvents\":[],\"pointers\":[],\"preparedUpgrades\":[]," + + "\"schemaVersion\":2,\"sharedNamespaces\":[],\"targetNamespace\":\"" + + namespace + + "\"}"; + return GameSessionRetainedTenantSnapshot.fromCanonicalJson( + namespace, legacyKey, canonicalJson, framedDigest(SNAPSHOT_DOMAIN, canonicalJson)); + } + + private static String framedDigest(String... segments) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + digest.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + digest.update((byte) ':'); + digest.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new AssertionError("SHA-256 unavailable for retained-association fixture", exception); + } + } } From c5bebbf4d97cc08cefa0986faa69948102a75b45 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:43:32 +1300 Subject: [PATCH 09/22] test(unit1b): bind command fixtures to retained tenant UUID evidence --- .github/workflows/ci.yml | 3 + .../player-access-and-session.md | 4 +- .../test/AccountRuntimeStubServerTest.java | 220 +++++++++++++++++- .../test/AccountRuntimeStubServer.java | 58 +++-- .../game-session-service/build.gradle.kts | 1 + ...tAssociationRepositoryIntegrationTest.java | 97 ++++++++ .../gamesession/CrossServiceAppHarness.java | 3 + .../GameplayCrossServiceStack.java | 43 +++- .../RetainedDemoTenantAssociationFixture.java | 208 +++++++++++++++++ 9 files changed, 609 insertions(+), 28 deletions(-) create mode 100644 services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/RetainedDemoTenantAssociationFixture.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a45453b78f..4b34773f90 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -991,6 +991,9 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#serviceReturnsExactCommittedAssociationAfterOwnerTransaction()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#serviceRecoversPostCommitReadFailureWithoutRewritingHistoricalAssociation()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDemoFixtureRegistersSnapshotAndResolvesItsDeclaredCanonicalTenant()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDemoFixtureReusesHistoricalReceiptAfterMutableSourceChanges()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDemoFixtureDoesNotInventUnknownOrContradictoryTenantMappings()' \ game-session-service - name: Upload Game Session retained tenant UUID PostgreSQL proof results 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 bdec90b5d4..ae3f2670c7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The shared command-test Account server now requires and preserves the exact canonical tenant UUID across membership evidence, maps, streams, checkpoints and request echoes, rejecting malformed identifiers without evidence. Its six direct RPC tests executed without skips or failures. The retained demo command fixture declares one arbitrary UUID association for its private tenant key, captures and commits real local snapshot/association evidence, and checks the production read-only resolver; later baselines and restarted fixture objects must reuse the complete historical receipt. Three PostgreSQL composition cases cover registration/resolution, immutable retry after source changes, and unknown or contradictory mapping/configuration. Their synthetic Game Design approval is explicitly test-only, not authenticated owner handoff or live catalog proof. Local database execution and composed transport proof remain unavailable without Docker; runtime activation and the response-envelope ring mount remain denied. + The current combined [#2933](https://github.com/benhook1013/FireMUD/pull/2933) absorbs the retained tenant-UUID consumer formerly packaged as #2935; separate Account-source and Game Session-consumer proof remains attributed below. Exact-head [CI 36947366507](https://github.com/benhook1013/FireMUD/actions/runs/36947366507) at `194eae43c6d10b2f5d476d7a65baae4ee3e44bc3` strictly executed all six password-reset producer and both required application cases once without skips, failures or errors. Game Session's component step executed four snapshot and eleven association cases cleanly, including both retained-key UUID lookup methods. These counts are strict job-log evidence: the Account artifact retained only the application XML, and the Game Session artifact missed its long XML filename. Class-bounded artifact globs correct that capture defect without changing suite/case requirements. The aggregate run failed, and the later broad Game Session task was canceled after cross-service assertions; full transport/admission proof remains open, not presumed inherited or fixed by these successful components. -The unwired retained-association service now performs exact committed-outcome readback after its owner transaction, comparing the complete immutable receipt rather than reporting the transaction-local result alone. An unavailable or contradictory read cannot authorize success or trigger repair; retry retains the original request and historical association. Its affected full Game Session check and JAR passed with formatting, Checkstyle, SpotBugs and JaCoCo: 123 tasks, 35 executed and 88 up-to-date. Game Session executed 1,813 unit cases, including all thirteen service cases, eighteen non-PostgreSQL integration cases and one cross-service case without failures/errors; seventeen unit, 139 integration and 33 cross-service cases skipped. All thirteen association PostgreSQL cases compiled but skipped without local Docker, including the two new service composition cases. The earlier exact-head component proof does not attest those two new cases. Audited source registration/import invocation, approval custody and live authenticated receiver proof remain open, with membership, credentials, catalog activation and the Account ring mount denied. +The unwired retained-association service performs exact committed-outcome readback after its owner transaction, comparing the complete immutable receipt rather than reporting the transaction-local result alone. An unavailable or contradictory read cannot authorize success or trigger repair; retry retains the original request and historical association. Exact-head [CI 36950170335](https://github.com/benhook1013/FireMUD/actions/runs/36950170335) at `0a3f22758acb47b482813698a035cf2085187615` executed all thirteen association PostgreSQL cases, including both service composition cases, and all eight required Account reset cases without skips, failures or errors. Its artifacts contain the intended two Account XML files and the full association XML. The aggregate remained red: broader Game Session communication tests reached the job timeout, TCP transport assertions failed, and other named service/tool checks failed. Those results do not negate successful component execution or establish complete transport proof. The subsequent fixture correction passed combined Common Test Support, Game Session and TCP checks: Game Session unit 1,813 executed/17 skipped, integration 18 executed/142 skipped, cross-service 1 executed/33 skipped; TCP unit 194, integration 7 and cross-service 3 executed/14 skipped, all without failures/errors. All sixteen association cases compiled but skipped locally without Docker, so the three new fixture-composition cases still need runner execution. Audited source registration/import invocation, approval custody and live authenticated receiver proof remain open, with membership, credentials, catalog activation and the Account ring mount denied. The retained Game Session tenant-UUID consumer candidate normally incorporates Account password-reset source #2933 `aa22f67be628748205414b954041cd003570d84b`. `PLAY` resolves only the exact workload-namespace/private-key association from an immutable owner-approved receipt, cross-reads its operation, request, canonical UUID and retained key, then uses that UUID in Account entitlement, membership and realm-grant requests and response comparisons. Missing configuration, missing association, nil or contradictory evidence denies without importer, roster or admission mutation. The full composed Account/Common Platform/Game Session checks, both service JARs, formatting/static analysis, links and Markdown passed166tasks(55executed/25from-cache/86up-to-date). Game Session newly executed1,806unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/137integration/33cross-service cases skipped. Its eleven retained-association PostgreSQL cases, including the two new lookup cases, compiled but skipped without Docker. Account526unit/167skipped PostgreSQL and Common Platform133unit results were reused from cache, not newly executed in this composed run. Normal ancestry preserves the complete Account/Common Platform parent subtree and all original Game Session candidate hunks byte-for-byte. This corrects the numeric tenant request boundary, not audited importer/source registration, fresh runtime catalog enrollment, complete typed entitlement/grant evidence, UUID-aware Game Logic/Social/moderation consumers, authenticated positive transport proof or runtime activation. The membership RPC, credential paths and Account ring mount remain denied. diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index 7fc1dd6f56..a11cd04ead 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -6,12 +6,16 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.time.Instant; +import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.common.account.AccountProfileJson; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; @@ -19,6 +23,7 @@ class AccountRuntimeStubServerTest { private static final String ACCOUNT_UUID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + private static final String TENANT_UUID = "784e0d9c-714f-4a22-9404-04b8b37c8ef1"; private static final String NIL_ACCOUNT_UUID = "00000000-0000-0000-0000-000000000000"; @Test @@ -46,7 +51,7 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio .setPlayerContext( net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setTenantId("1") + .setTenantId(TENANT_UUID) .setRequestId("request-1")) .build(); Instant activeBefore = Instant.now(); @@ -57,7 +62,7 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio assertThat(active.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(active.getRequestId()).isEqualTo("request-1"); assertThat(active.getMembershipAuthorityGeneration()).isEqualTo("1"); - assertMembershipEventMatches(active, "ACTIVE", true); + assertMembershipEventMatches(active, "ACTIVE", true, "request-1"); assertThat(Instant.parse(active.getEvaluatedAt())).isBetween(activeBefore, activeAfter); var secondRequest = @@ -67,7 +72,7 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio .build(); var secondActive = stub.getTenantMembershipForRuntime(secondRequest); assertThat(secondActive.getRequestId()).isEqualTo("request-2"); - assertMembershipEventMatches(secondActive, "ACTIVE", true); + assertMembershipEventMatches(secondActive, "ACTIVE", true, "request-2"); assertThat(secondActive.getOutboxSourceEvidence(0).getCanonicalEventJson()) .isEqualTo(active.getOutboxSourceEvidence(0).getCanonicalEventJson()); assertThat(secondActive.getOutboxSourceEvidence(0).getEventDigest()) @@ -84,7 +89,7 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio assertThat(inactive.hasAuthorityTuple()).isTrue(); assertThat(inactive.getOutboxCheckpointsCount()).isEqualTo(4); assertThat(inactive.getOutboxSourceEvidenceCount()).isEqualTo(1); - assertMembershipEventMatches(inactive, "INACTIVE", false); + assertMembershipEventMatches(inactive, "INACTIVE", false, "request-1"); assertThat(Instant.parse(inactive.getEvaluatedAt())) .isBetween(inactiveBefore, inactiveAfter); @@ -95,7 +100,7 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); - assertThat(membership.getOutboxSourceEvidenceCount()).isZero(); + assertMembershipSnapshotMatches(membership, "MISSING", false, false, "request-1", "0"); assertThat(Instant.parse(membership.getEvaluatedAt())) .isBetween(missingBefore, missingAfter); } finally { @@ -104,18 +109,158 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio } } + @Test + void rejectsNonCanonicalRuntimeTenantIdsWithoutReturningMembershipEvidence() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + List invalidTenantIds = + List.of( + "1", + "00000000-0000-0000-0000-000000000000", + TENANT_UUID.toUpperCase(Locale.ROOT), + "not-a-uuid"); + + for (int index = 0; index < invalidTenantIds.size(); index++) { + String tenantId = invalidTenantIds.get(index); + var response = + stub.withDeadlineAfter(1, TimeUnit.SECONDS) + .getTenantMembershipForRuntime(membershipRequest(tenantId, "invalid-" + index)); + + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(response.getError().getMessage()).isNotEmpty(); + assertThat(response.getAccountId()).isEmpty(); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getRequestAccountId()).isEmpty(); + assertThat(response.getRequestTenantId()).isEmpty(); + assertThat(response.getRequestId()).isEmpty(); + assertThat(response.getAuthorityAvailability()).isEmpty(); + assertThat(response.getMembershipVersionMap()).isEmpty(); + assertThat(response.getOutboxCheckpointsCount()).isZero(); + assertThat(response.getOutboxSourceEvidenceCount()).isZero(); + assertThat(response.hasMembershipBaseline()).isFalse(); + assertThat(response.hasAuthorityTuple()).isFalse(); + } + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void contradictoryMembershipLifecycleAndAdmissionRemainDenied() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + + server.setGameplayAdmissionAllowed(false); + var activeButDenied = + stub.getTenantMembershipForRuntime(membershipRequest(TENANT_UUID, "contradictory-1")); + assertContradictoryMembershipDenied(activeButDenied, "ACTIVE", "contradictory-1"); + + server.denyGameplayAdmission(); + server.setGameplayAdmissionAllowed(true); + var inactiveButAllowed = + stub.getTenantMembershipForRuntime(membershipRequest(TENANT_UUID, "contradictory-2")); + assertContradictoryMembershipDenied(inactiveButAllowed, "INACTIVE", "contradictory-2"); + } finally { + channel.shutdownNow(); + } + } + } + + private static GetTenantMembershipForRuntimeRequest membershipRequest( + String tenantId, String requestId) { + return GetTenantMembershipForRuntimeRequest.newBuilder() + .setPlayerContext( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId(tenantId) + .setRequestId(requestId)) + .build(); + } + + private static void assertContradictoryMembershipDenied( + GetTenantMembershipForRuntimeResponse response, String lifecycle, String requestId) { + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getRequestTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestId()).isEqualTo(requestId); + assertThat(response.getMembershipExists()).isTrue(); + assertThat(response.getMembershipLifecycleState()).isEqualTo(lifecycle); + assertThat(response.getGameplayAdmissionAllowed()).isFalse(); + assertThat(response.getAuthorityAvailability()).isEmpty(); + assertThat(response.getMembershipVersionMap()).isEmpty(); + assertThat(response.getOutboxCheckpointsCount()).isZero(); + assertThat(response.getOutboxSourceEvidenceCount()).isZero(); + assertThat(response.hasMembershipBaseline()).isFalse(); + assertThat(response.hasAuthorityTuple()).isFalse(); + } + private static void assertMembershipEventMatches( - GetTenantMembershipForRuntimeResponse response, String lifecycle, boolean admitted) { + GetTenantMembershipForRuntimeResponse response, + String lifecycle, + boolean admitted, + String requestId) { + assertMembershipSnapshotMatches(response, lifecycle, true, admitted, requestId, "1"); var source = response.getOutboxSourceEvidence(0); var event = MembershipAuthorityEventV1Codec.verify(source.getCanonicalEventJson()); + String membershipStream = + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID; + var expectedEvent = + MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "00000000-0000-0000-0000-000000000099"), + Map.entry("requestId", "runtime-membership-request"), + Map.entry("outboxStreamKey", membershipStream), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", "membership/" + ACCOUNT_UUID + "/" + TENANT_UUID), + Map.entry("accountId", ACCOUNT_UUID), + Map.entry("tenantId", TENANT_UUID), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", lifecycle), + Map.entry("membershipVersion", Map.of(TENANT_UUID, "1")), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_UUID, "1"), + "membershipAuthorityGeneration", Map.of(TENANT_UUID, "1"), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", admitted ? List.of("player") : List.of()), + Map.entry("gameplayAdmissionAllowed", admitted), + Map.entry("callerBoundAuthorityInvalidated", false))); + assertThat(event.canonicalJson()).isEqualTo(source.getCanonicalEventJson()); + assertThat(event.canonicalJson()).isEqualTo(expectedEvent.canonicalJson()); assertThat(event.eventDigest()).isEqualTo(source.getEventDigest()); + assertThat(event.eventDigest()).isEqualTo(expectedEvent.eventDigest()); + assertThat(event.schemaVersion()).isEqualTo(MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + assertThat(event.eventType()).isEqualTo(MembershipAuthorityEventV1Codec.EVENT_TYPE); assertThat(event.eventId()).isEqualTo(source.getEventId()); + assertThat(event.requestId()).isEqualTo("runtime-membership-request"); assertThat(event.accountId()).isEqualTo(response.getAccountId()); assertThat(event.tenantId()).isEqualTo(response.getTenantId()); + assertThat(event.sourceScope()).isEqualTo("membership/" + ACCOUNT_UUID + "/" + TENANT_UUID); + assertThat(event.outboxStreamKey()).isEqualTo(membershipStream); assertThat(event.outboxStreamKey()).isEqualTo(source.getOutboxStreamKey()); + assertThat(event.outboxSequence()).isEqualTo("1"); assertThat(event.outboxSequence()).isEqualTo(source.getOutboxSequence()); assertThat(event.membershipLifecycleState()).isEqualTo(lifecycle); + assertThat(event.membershipVersion()).containsExactlyEntriesOf(Map.of(TENANT_UUID, "1")); assertThat(event.membershipVersion()).isEqualTo(response.getMembershipVersionMap()); assertThat(event.membershipAuthorityGeneration()) .isEqualTo(response.getMembershipAuthorityGeneration()); @@ -133,6 +278,69 @@ private static void assertMembershipEventMatches( assertThat(event.gameplayAdmissionAllowed()).isEqualTo(admitted); } + private static void assertMembershipSnapshotMatches( + GetTenantMembershipForRuntimeResponse response, + String lifecycle, + boolean exists, + boolean admitted, + String requestId, + String membershipSequence) { + String membershipStream = + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID; + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getRequestTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestId()).isEqualTo(requestId); + assertThat(response.getAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(response.getMembershipExists()).isEqualTo(exists); + assertThat(response.getMembershipLifecycleState()).isEqualTo(lifecycle); + assertThat(response.getGameplayAdmissionAllowed()).isEqualTo(admitted); + assertThat(response.getMembershipVersionMap()) + .containsExactlyEntriesOf(Map.of(TENANT_UUID, "1")); + assertThat(response.getMembershipAuthorityGeneration()).isEqualTo("1"); + assertThat(response.hasMembershipBaseline()).isTrue(); + assertThat(response.getMembershipBaseline().getMembershipLifecycleState()).isEqualTo(lifecycle); + assertThat(response.getMembershipBaseline().getMembershipVersionMap()) + .containsExactlyEntriesOf(Map.of(TENANT_UUID, "1")); + assertThat(response.getMembershipBaseline().getMembershipAuthorityGeneration()).isEqualTo("1"); + assertThat(response.hasAuthorityTuple()).isTrue(); + assertThat(response.getAuthorityTuple().getIssuerAuthGeneration()).isEqualTo("1"); + assertThat(response.getAuthorityTuple().getAccountAuthorityGeneration()).isEqualTo("1"); + assertThat(response.getAuthorityTuple().getTenantAuthorityGenerationMap()) + .containsExactlyEntriesOf(Map.of(TENANT_UUID, "1")); + assertThat(response.getAuthorityTuple().getMembershipAuthorityGenerationMap()) + .containsExactlyEntriesOf(Map.of(TENANT_UUID, "1")); + assertThat(response.getAuthorityTuple().getPrivateRealmGrantVersionsList()).isEmpty(); + assertThat(response.getAuthorityTuple().hasAccountSecurityCutoff()).isFalse(); + assertThat(response.getAuthorityTuple().hasTenantBillingCutoff()).isFalse(); + assertThat(response.getIssuanceFence()).isEqualTo("1"); + assertThat(response.getRolesList()) + .containsExactlyElementsOf(admitted ? List.of("player") : List.of()); + assertThat(response.getOutboxCheckpointsList()) + .containsExactly( + checkpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID, "0"), + checkpoint("account:auth-authority:v1:issuer/firemud-account-service", "0"), + checkpoint(membershipStream, membershipSequence), + checkpoint("account:auth-authority:v1:tenant/" + TENANT_UUID, "0")); + assertThat(response.getOutboxSourceEvidenceCount()).isEqualTo(exists ? 1 : 0); + if (exists) { + var source = response.getOutboxSourceEvidence(0); + assertThat(source.getOutboxStreamKey()).isEqualTo(membershipStream); + assertThat(source.getOutboxSequence()).isEqualTo("1"); + assertThat(source.getCanonicalEventJson()).isNotEmpty(); + assertThat(source.getEventId()).isNotEmpty(); + assertThat(source.getEventDigest()).matches("sha256:[0-9a-f]{64}"); + } + } + + private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String sequence) { + return RuntimeOutboxCheckpoint.newBuilder() + .setOutboxStreamKey(streamKey) + .setOutboxSequence(sequence) + .build(); + } + @Test void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index ad125758d0..e927759ef2 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -7,7 +7,6 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -183,35 +182,50 @@ public void authenticate( public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { + String accountUuid; + String tenantUuid; + try { + accountUuid = requireCanonicalAccountUuid(request.getPlayerContext().getAccountId()); + tenantUuid = requireCanonicalTenantUuid(request.getPlayerContext().getTenantId()); + } catch (IllegalArgumentException exception) { + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Runtime membership context requires canonical non-nil UUIDs")) + .build()); + responseObserver.onCompleted(); + return; + } + boolean exists = membershipExists.get(); - String accountUuid = requireCanonicalAccountUuid(request.getPlayerContext().getAccountId()); - String tenantSelector = request.getPlayerContext().getTenantId(); String lifecycle = membershipLifecycleState.get(); boolean admitted = gameplayAdmissionAllowed.get(); GetTenantMembershipForRuntimeResponse response; if (exists && admitted && "ACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle); + accountUuid, tenantUuid, request.getPlayerContext().getRequestId(), lifecycle); } else if (exists && !admitted && "INACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle); + accountUuid, tenantUuid, request.getPlayerContext().getRequestId(), lifecycle); } else if (!exists && !admitted && "MISSING".equals(lifecycle)) { response = completeMembershipSnapshot( - accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle); + accountUuid, tenantUuid, request.getPlayerContext().getRequestId(), lifecycle); } else { response = GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) - .setTenantId(syntheticTenantUuid(tenantSelector)) + .setTenantId(tenantUuid) .setRequestAccountId(accountUuid) - .setRequestTenantId(tenantSelector) + .setRequestTenantId(tenantUuid) .setRequestId(request.getPlayerContext().getRequestId()) .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) - .setGameplayAdmissionAllowed(admitted) + .setGameplayAdmissionAllowed(false) .setEvaluatedAt(Instant.now().toString()) .build(); } @@ -220,10 +234,9 @@ public void getTenantMembershipForRuntime( } private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( - String accountUuid, String tenantSelector, String requestId, String lifecycle) { + String accountUuid, String tenantUuid, String requestId, String lifecycle) { boolean exists = !"MISSING".equals(lifecycle); boolean admitted = "ACTIVE".equals(lifecycle); - String tenantUuid = syntheticTenantUuid(tenantSelector); String membershipStream = AUTHORITY_STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = @@ -253,7 +266,7 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( .setAccountId(accountUuid) .setTenantId(tenantUuid) .setRequestAccountId(accountUuid) - .setRequestTenantId(tenantSelector) + .setRequestTenantId(tenantUuid) .setRequestId(requestId) .setAuthorityAvailability("AVAILABLE") .setMembershipExists(exists) @@ -333,14 +346,21 @@ private static String requireCanonicalAccountUuid(String selector) { return selector; } - private static String syntheticTenantUuid(String selector) { - // This stable UUID-shaped key is only a legacy synthetic-tenant test fixture. It is not - // evidence of an Account-owned tenant identity or an authenticated membership snapshot. - long value = Long.parseLong(selector); - if (value <= 0L || !Long.toString(value).equals(selector)) { - throw new IllegalArgumentException("synthetic tenant fixture selector must be canonical"); + private static String requireCanonicalTenantUuid(String tenantUuid) { + if (tenantUuid == null) { + throw new IllegalArgumentException("Tenant UUID must be canonical and non-nil"); + } + UUID parsed; + try { + parsed = UUID.fromString(tenantUuid); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Tenant UUID must be canonical and non-nil", exception); + } + if ((parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) + || !parsed.toString().equals(tenantUuid)) { + throw new IllegalArgumentException("Tenant UUID must be canonical and non-nil"); } - return "00000000-0000-0000-0000-" + String.format(Locale.ROOT, "%012d", value); + return tenantUuid; } @Override diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index f1cc7d92b6..bf0c7c7612 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -73,6 +73,7 @@ dependencies { testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}") testFixturesImplementation("com.google.protobuf:protobuf-java:${libs.versions.protobuf.get()}") testFixturesImplementation(libs.spring.boot.starter.jdbc) + testFixturesImplementation("org.jooq:jooq") testFixturesCompileOnly(libs.testcontainers.postgresql) testFixturesCompileOnly(libs.testcontainers) testImplementation(libs.grpc.inprocess) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index fcc6165c83..e1081cd5fa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -41,6 +41,8 @@ import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; import net.firedevops.firemud.gamesession.service.GameSessionRetainedTenantAssociationService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; +import net.firedevops.firemud.gamesession.testsupport.RetainedDemoTenantAssociationFixture; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; @@ -70,6 +72,88 @@ class GameSessionRetainedTenantAssociationRepositoryIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Test + void syntheticDemoFixtureRegistersSnapshotAndResolvesItsDeclaredCanonicalTenant() { + Fixture fixture = fixture(); + fixture.seedInstance(1L, 101L, "demo-runtime-v1"); + RetainedDemoTenantAssociationFixture demoFixture = fixture.demoTenantAssociationFixture(); + + AssociationReceipt receipt = demoFixture.ensureAssociation(1L).orElseThrow(); + + assertThat(receipt.approval().canonicalTenantId()) + .isEqualTo(RetainedDemoTenantAssociationFixture.DEMO_CANONICAL_TENANT_ID); + assertThat(receipt.approval().legacyGameSessionTenantIdValue()).isEqualTo(1L); + assertThat(receipt.approval().gameSessionEvidenceDigest()) + .isEqualTo(receipt.snapshot().evidenceDigest()); + assertThat(receipt.snapshot().canonicalJson()).contains("demo-runtime-v1"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.associationRequestId(), + RetainedDemoTenantAssociationFixture.DEMO_CANONICAL_TENANT_ID, + 1L, + NAMESPACE)) + .contains(receipt); + assertThat(fixture.demoResolver().resolveCanonicalTenantId(1L)) + .contains(RetainedDemoTenantAssociationFixture.DEMO_CANONICAL_TENANT_ID); + assertThat(fixture.associationXmin(receipt.associationRequestId())).isNotBlank(); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void syntheticDemoFixtureReusesHistoricalReceiptAfterMutableSourceChanges() { + Fixture fixture = fixture(); + fixture.seedInstance(1L, 101L, "demo-runtime-before-change"); + RetainedDemoTenantAssociationFixture demoFixture = fixture.demoTenantAssociationFixture(); + AssociationReceipt original = demoFixture.ensureAssociation(1L).orElseThrow(); + String associationXmin = fixture.associationXmin(original.associationRequestId()); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "demo-runtime-after-change", + 101L); + + assertThat(fixture.capture(1L).evidenceDigest()) + .isNotEqualTo(original.snapshot().evidenceDigest()); + assertThat(fixture.demoTenantAssociationFixture().ensureAssociation(1L)).contains(original); + assertThat(demoFixture.ensureAssociation(1L)).contains(original); + assertThat(fixture.associationXmin(original.associationRequestId())).isEqualTo(associationXmin); + assertThat(fixture.demoResolver().resolveCanonicalTenantId(1L)) + .contains(RetainedDemoTenantAssociationFixture.DEMO_CANONICAL_TENANT_ID); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void syntheticDemoFixtureDoesNotInventUnknownOrContradictoryTenantMappings() { + Fixture fixture = fixture(); + fixture.seedInstance(1L, 101L, "demo-runtime-v1"); + RetainedDemoTenantAssociationFixture demoFixture = fixture.demoTenantAssociationFixture(); + AssociationReceipt receipt = demoFixture.ensureAssociation(1L).orElseThrow(); + + assertThat(demoFixture.ensureAssociation(2L)).isEmpty(); + assertThat(fixture.demoResolver().resolveCanonicalTenantId(2L)).isEmpty(); + assertThat( + new RetainedRuntimeTenantUuidResolver( + new GameSessionRetainedTenantAssociationRepository( + fixture.dsl, fixture.snapshotRepository, "other-game-session-test"), + "other-game-session-test", + Objects.requireNonNull(fixture.transactions.getTransactionManager())) + .resolveCanonicalTenantId(1L)) + .isEmpty(); + assertThat(RetainedRuntimeTenantUuidResolver.denyOnly("").resolveCanonicalTenantId(1L)) + .isEmpty(); + assertThatThrownBy( + () -> + fixture.repository.read( + receipt.operationId(), + receipt.associationRequestId(), + UUID.fromString("528846b9-08e8-4c4f-9e3a-e6997a523730"), + 1L, + NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + @Test void exactRetryReturnsHistoricalReceiptWithoutRecapturingChangedSource() { Fixture fixture = fixture(); @@ -839,6 +923,19 @@ private record Fixture( GameSessionRetainedTenantSnapshotRepository snapshotRepository, GameSessionRetainedTenantAssociationRepository repository, TransactionTemplate transactions) { + RetainedDemoTenantAssociationFixture demoTenantAssociationFixture() { + return new RetainedDemoTenantAssociationFixture( + dsl, + snapshotRepository, + Objects.requireNonNull(transactions.getTransactionManager()), + NAMESPACE); + } + + RetainedRuntimeTenantUuidResolver demoResolver() { + return new RetainedRuntimeTenantUuidResolver( + repository, NAMESPACE, Objects.requireNonNull(transactions.getTransactionManager())); + } + void seedInstance(long tenantId, long instanceId, String runtimeVersion) { dsl.execute( "INSERT INTO game_instances " diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 0574f4f54d..3f9aa9192d 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -36,6 +36,8 @@ /** Shared bootstrap helpers for nested cross-service Spring application contexts in tests. */ public final class CrossServiceAppHarness { + public static final String TEST_WORKLOAD_NAMESPACE = "gameplay-cross-service-test"; + private static final String CROSS_SERVICE_TEST_JWT_SECRET = "stub-secret-key-for-tests-1234567890"; @@ -123,6 +125,7 @@ public static GameSessionHolder startGameSession( props.put("spring.main.allow-bean-definition-overriding", "true"); props.put("spring.flyway.enabled", "true"); props.put("spring.flyway.locations", "filesystem:" + gameSessionMigrationDir()); + props.put("firemud.grpc.workload-namespace", TEST_WORKLOAD_NAMESPACE); props.put( "spring.autoconfigure.exclude", "org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration," diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 297effcac9..d0d40ba4f2 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -7,12 +7,16 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import javax.sql.DataSource; import net.firedevops.firemud.cache.ScreenBufferService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.CrossServiceAppHarness; import net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.test.GameInstanceTestFixtures; @@ -23,8 +27,10 @@ import net.firedevops.firemud.gamesession.test.stubs.WorldManagementStubServer; import net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse; import net.firedevops.firemud.test.AccountRuntimeStubServer; +import org.jooq.DSLContext; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.PlatformTransactionManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -44,6 +50,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final Map syntheticManagementOwnerUuidsBySelector = new HashMap<>(); private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; + private final RetainedDemoTenantAssociationFixture retainedDemoTenantAssociationFixture; private GameplayCrossServiceStack( AccountRuntimeStubServer accountStub, @@ -54,7 +61,8 @@ private GameplayCrossServiceStack( net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse baselineRoomEntities, ListFriendPresenceResponse baselineFriendPresenceResponse, CrossServiceAppHarness.GameLogicHolder gameLogic, - CrossServiceAppHarness.GameSessionHolder gameSession) { + CrossServiceAppHarness.GameSessionHolder gameSession, + String workloadNamespace) { this.accountStub = accountStub; this.gameDesignStub = gameDesignStub; this.worldStub = worldStub; @@ -64,6 +72,14 @@ private GameplayCrossServiceStack( this.baselineFriendPresenceResponse = baselineFriendPresenceResponse; this.gameLogic = gameLogic; this.gameSession = gameSession; + this.retainedDemoTenantAssociationFixture = + GrpcPeerIdentity.isValidNamespace(workloadNamespace) + ? new RetainedDemoTenantAssociationFixture( + gameSession.bean(DSLContext.class), + gameSession.bean(GameSessionRetainedTenantSnapshotRepository.class), + gameSession.bean(PlatformTransactionManager.class), + workloadNamespace) + : null; } public static Builder builder() { @@ -189,6 +205,23 @@ public long freshGameplayBaseline( GameInstanceTestFixtures.insertRunningGameInstance( jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); + if (retainedDemoTenantAssociationFixture != null) { + retainedDemoTenantAssociationFixture.ensureAssociation(tenantId); + } + if (retainedDemoTenantAssociationFixture != null + && tenantId == RetainedDemoTenantAssociationFixture.DEMO_LEGACY_TENANT_ID) { + Optional resolvedTenantId = + gameSession + .bean(RetainedRuntimeTenantUuidResolver.class) + .resolveCanonicalTenantId(tenantId); + if (resolvedTenantId.isEmpty() + || !resolvedTenantId + .orElseThrow() + .equals(RetainedDemoTenantAssociationFixture.DEMO_CANONICAL_TENANT_ID)) { + throw new IllegalStateException( + "Production retained-tenant resolver did not read the declared demo UUID association"); + } + } return gameInstanceId; } @@ -431,6 +464,11 @@ public Builder withGameSessionConfigs(Class... configs) { public GameplayCrossServiceStack start() throws IOException { requireConfigured(); + String workloadNamespace = + String.valueOf( + gameSessionProps.getOrDefault( + "firemud.grpc.workload-namespace", + CrossServiceAppHarness.TEST_WORKLOAD_NAMESPACE)); AccountRuntimeStubServer accountStub = new AccountRuntimeStubServer(0); accountStub.setDefaultAccountUuid(defaultAccountUuid); accountUuidMappings.forEach(accountStub::mapAccountUuid); @@ -490,7 +528,8 @@ public GameplayCrossServiceStack start() throws IOException { initialRoomEntities, initialFriendPresenceResponse, gameLogic, - gameSession); + gameSession, + workloadNamespace); } private void requireConfigured() { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/RetainedDemoTenantAssociationFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/RetainedDemoTenantAssociationFixture.java new file mode 100644 index 0000000000..e7fdddaed8 --- /dev/null +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/RetainedDemoTenantAssociationFixture.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamesession.testsupport; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.util.Base64; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Synthetic immutable owner evidence for the demo retained-tenant command-test fixture. + * + *

The signed source metadata is synthetic and does not establish a real Game Design source row, + * authenticated peer, or live owner approval. + */ +public final class RetainedDemoTenantAssociationFixture { + public static final long DEMO_LEGACY_TENANT_ID = 1L; + public static final UUID DEMO_CANONICAL_TENANT_ID = + UUID.fromString("32ef3d8c-af20-4eb0-85cb-4339a03a618a"); + + private static final UUID APPROVAL_OPERATION_ID = + UUID.fromString("25a881bb-2200-4528-af0a-abbd67041944"); + private static final UUID ASSOCIATION_REQUEST_ID = + UUID.fromString("45ec8370-f5e7-44ad-8bc7-bdbdafc4ae36"); + private static final long SYNTHETIC_SOURCE_GAME_ROW_ID = 900001L; + private static final String SYNTHETIC_SOURCE_GAME_TENANT_KEY = "demo-owner-fixture"; + private static final String SYNTHETIC_SIGNER_KEY_ID = "synthetic-demo-owner-key"; + private static final String SYNTHETIC_APPROVED_BY = "synthetic-demo-fixture"; + private static final String SYNTHETIC_APPROVAL_REFERENCE = "synthetic-command-test-only"; + private static final String SYNTHETIC_SIGNED_AT = "2026-01-01T00:00:00Z"; + + private final DSLContext dsl; + private final GameSessionRetainedTenantSnapshotRepository snapshotRepository; + private final GameSessionRetainedTenantAssociationRepository associationRepository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + private AssociationReceipt committedReceipt; + + public RetainedDemoTenantAssociationFixture( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.snapshotRepository = + Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); + this.workloadNamespace = Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + this.associationRepository = + new GameSessionRetainedTenantAssociationRepository( + dsl, snapshotRepository, workloadNamespace); + this.ownerTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Registers once, after the fixture has inserted its actual Game Session rows, then returns the + * exact committed historical receipt on later baselines. Other retained keys stay unmapped. + */ + public synchronized Optional ensureAssociation(long legacyTenantId) { + if (legacyTenantId != DEMO_LEGACY_TENANT_ID) { + return Optional.empty(); + } + if (committedReceipt != null) { + return Optional.of(readExact(committedReceipt)); + } + + AssociationReceipt existing = readExistingFixtureAssociation(); + if (existing != null) { + committedReceipt = existing; + return Optional.of(existing); + } + + GameSessionRetainedTenantSnapshot captured = + Objects.requireNonNull( + ownerTransaction.execute( + status -> + snapshotRepository.capture( + workloadNamespace, Long.toString(DEMO_LEGACY_TENANT_ID))), + "fixture snapshot capture must return evidence"); + LegacyGameSessionTenantAssociationReceipt approval = syntheticApproval(captured); + AssociationReceipt registered = + Objects.requireNonNull( + ownerTransaction.execute( + status -> associationRepository.register(ASSOCIATION_REQUEST_ID, approval)), + "fixture association registration must return a receipt"); + AssociationReceipt committed = readExact(registered); + if (!registered.equals(committed)) { + throw new IllegalStateException( + "Synthetic demo tenant association committed readback contradicts registration"); + } + committedReceipt = committed; + return Optional.of(committed); + } + + private AssociationReceipt readExistingFixtureAssociation() { + Record row = + dsl.fetchOne( + "SELECT operation_id, association_request_id, canonical_tenant_id " + + "FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND legacy_game_session_tenant_id = ?", + workloadNamespace, + DEMO_LEGACY_TENANT_ID); + if (row == null) { + return null; + } + UUID operationId = Objects.requireNonNull(row.get("operation_id", UUID.class)); + UUID requestId = Objects.requireNonNull(row.get("association_request_id", UUID.class)); + UUID canonicalTenantId = Objects.requireNonNull(row.get("canonical_tenant_id", UUID.class)); + if (!ASSOCIATION_REQUEST_ID.equals(requestId) + || !DEMO_CANONICAL_TENANT_ID.equals(canonicalTenantId)) { + throw new IllegalStateException( + "Existing demo retained-tenant association contradicts its declared fixture identity"); + } + AssociationReceipt receipt = + associationRepository + .read( + operationId, requestId, canonicalTenantId, DEMO_LEGACY_TENANT_ID, workloadNamespace) + .orElseThrow( + () -> + new IllegalStateException( + "Existing demo retained-tenant association readback is missing")); + requireSyntheticApproval(receipt); + return receipt; + } + + private AssociationReceipt readExact(AssociationReceipt expected) { + AssociationReceipt actual = + associationRepository + .read( + expected.operationId(), + ASSOCIATION_REQUEST_ID, + DEMO_CANONICAL_TENANT_ID, + DEMO_LEGACY_TENANT_ID, + workloadNamespace) + .orElseThrow( + () -> + new IllegalStateException( + "Committed demo retained-tenant association readback is missing")); + requireSyntheticApproval(actual); + if (!expected.equals(actual)) { + throw new IllegalStateException( + "Historical demo retained-tenant association changed after committed readback"); + } + return actual; + } + + private LegacyGameSessionTenantAssociationReceipt syntheticApproval( + GameSessionRetainedTenantSnapshot snapshot) { + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + 1, + APPROVAL_OPERATION_ID, + workloadNamespace, + SYNTHETIC_SIGNER_KEY_ID, + SYNTHETIC_APPROVED_BY, + SYNTHETIC_APPROVAL_REFERENCE, + SYNTHETIC_SIGNED_AT, + Long.toString(DEMO_LEGACY_TENANT_ID), + DEMO_CANONICAL_TENANT_ID, + Long.toString(SYNTHETIC_SOURCE_GAME_ROW_ID), + SYNTHETIC_SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW", + snapshot.evidenceDigest()); + try { + KeyPair keyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Signature signer = Signature.getInstance("Ed25519"); + signer.initSign(keyPair.getPrivate()); + signer.update(evidence.preimage()); + String signature = Base64.getEncoder().encodeToString(signer.sign()); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, evidence.manifestDigest(), signature); + } catch (Exception exception) { + throw new IllegalStateException("Could not sign synthetic demo owner evidence", exception); + } + } + + private static void requireSyntheticApproval(AssociationReceipt receipt) { + GameSessionTenantAssociationEvidence approval = receipt.approval(); + if (!ASSOCIATION_REQUEST_ID.equals(receipt.associationRequestId()) + || !APPROVAL_OPERATION_ID.equals(approval.operationId()) + || !DEMO_CANONICAL_TENANT_ID.equals(approval.canonicalTenantId()) + || approval.legacyGameSessionTenantIdValue() != DEMO_LEGACY_TENANT_ID + || approval.sourceGameRowIdValue() != SYNTHETIC_SOURCE_GAME_ROW_ID + || !SYNTHETIC_SOURCE_GAME_TENANT_KEY.equals(approval.sourceGameTenantKey()) + || !SYNTHETIC_SIGNER_KEY_ID.equals(approval.signerKeyId()) + || !SYNTHETIC_APPROVED_BY.equals(approval.approvedBy()) + || !SYNTHETIC_APPROVAL_REFERENCE.equals(approval.approvalReference()) + || !SYNTHETIC_SIGNED_AT.equals(approval.signedAt())) { + throw new IllegalStateException( + "Persisted demo association does not contain the declared synthetic owner evidence"); + } + } +} From 8344e6ea134ccbe52a90e4c554b2fee770ad53a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:28:03 +1300 Subject: [PATCH 10/22] Add atomic issuer authority source proof and preserve fixture pointer targets --- .github/workflows/ci.yml | 30 + .../account-service/api-contracts.md | 8 + .../system-architecture-authentication.md | 8 + .../player-access-and-session.md | 4 + .../AccountIssuerAuthorityEventProducer.java | 573 +++++++++++++++++ ...horityProducerPostgresIntegrationTest.java | 586 ++++++++++++++++++ ...countIssuerAuthorityEventProducerTest.java | 247 ++++++++ ...IssuerGenerationAuthorityEventV1Codec.java | 327 ++++++++++ ...th-issuer-generation-event-v1-vectors.json | 126 ++++ ...erGenerationAuthorityEventV1CodecTest.java | 194 ++++++ ...tAssociationRepositoryIntegrationTest.java | 127 +++- .../test/GameInstanceTestFixtures.java | 105 ++++ .../GameplayCrossServiceStack.java | 20 +- 13 files changed, 2348 insertions(+), 7 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4b34773f90..17cea92f9f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -994,6 +994,7 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDemoFixtureRegistersSnapshotAndResolvesItsDeclaredCanonicalTenant()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDemoFixtureReusesHistoricalReceiptAfterMutableSourceChanges()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDemoFixtureDoesNotInventUnknownOrContradictoryTenantMappings()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#syntheticDefaultPointerTargetsRemainValidAcrossRepeatedFixtureBaselines()' \ game-session-service - name: Upload Game Session retained tenant UUID PostgreSQL proof results @@ -1081,6 +1082,35 @@ jobs: fi echo "::endgroup::" + - name: Verify Account issuer authority PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#atomicallyAdvancesSourceAndEventAndReadsBackExactCheckpoint()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#exactRetryRecoversLostResponseAndOriginalEventAfterLaterAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#concurrentExactRequestSerializesAndCommitsOneSourceEvent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#changedExpectedStateForSameRequestConflictsWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#wrongIssuerStaleRequestAndMissingSourceFailWithoutEnrollmentOrMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#sequenceZeroRequiresOriginalPositiveBaselineAndNoContradictoryStreamOrHistory()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#positiveReadbackRejectsSourceCountersThatDifferFromLatestEvent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#positiveReadbackUsesExplicitLatestEventCountersInsteadOfDerivingThemFromSequence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#appendFailureRollsBackSourceAndOutboxTogether()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#transactionLocalEventReadbackFailureRollsBackTheAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#unavailablePostCommitReadDoesNotUndoAndExactRetryRecoversWithoutAdvancingAgain()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#generationAndSourceVersionOverflowFailBeforeAnyMutation()' \ + account-service + + - name: Upload Account issuer authority PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-issuer-authority-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*IssuerAuthorityProducerPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: 🔎 Verify Account password reset PostgreSQL proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 1c1925f5c7..5e0f18ef4e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -147,6 +147,14 @@ The private digest frame starts with its domain and then each field in the decla The stored receipt and event must be read back exactly before success, including after a lost response. Concurrent retries serialize on the exact Account/source scope and one-use token claim; token consumption, password mutation, authority advance, event append and receipt insertion roll back together on any failure. Receipt cleanup remains Account-owned and must prove its retained recovery/replay horizon, holds and references before deletion; expiry alone is not deletion proof and no fixed retention interval is invented here. The current candidate composes this Account-local producer and immutable receipt; it does not implement downstream event delivery, authenticated recipient readback, projection consumption, or active-binding termination. The capability and execution gates remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +### Account-Owned Issuer Authority Advance and Readback + +An issuer authority operation binds the exact configured Account `issuerId`, a caller-retained canonical non-nil UUID `requestId`, and the expected positive persisted generation and source version. Its operation identity is the exact `{issuerId, requestId}` pair; requests for another issuer are rejected, not redirected or normalized. One successful operation compare-and-advances both counters by one and commits the [issuer generation source event](../../system-architecture-authentication.md#issuer-generation-source-event) and outbox checkpoint atomically. Its stable event ID is `account-issuer-authority-event-v1:`; its complete immutable event binds the resulting counters, exact issuer scope and sequence. There is no individual Account selector or issuance fence. Missing, contradictory, stale or overflowed source evidence fails closed before reporting success; this operation does not enroll missing authority or rotate JWT keys. + +Exact retry first reads the immutable event for that request while holding the issuer-source fence. It verifies every event field, payload and digest against the original issuer/request and expected counters plus one, then returns the original event without advancing again. Reusing the same issuer/request pair with changed expected source state is rejected; concurrent exact attempts serialize on the same issuer row. A later valid source advance does not change the historical result, but historical recovery does not establish the current issuer checkpoint or authorize a recipient. A failed transaction must roll back source counters and outbox state together. No new retry identity is allocated to hide a lost response. + +Current source readback holds the same issuer fence and returns its positive generation/source version together with exact stream evidence from one Account snapshot. Sequence zero requires the original proved positive baseline and absence of all committed events and contradictory stream state, not merely an absent event/head row; event ID, digest and payload are omitted at zero. A positive checkpoint must exactly match the latest closed issuer event and current counters. Both mutation and readback remain owner-local, unwired components until the authenticated exact-method producer/consumer handoff, delivery and atomic Game Session projection proof pass. They must not be treated as an enabled revocation endpoint or an admission/rebind credential. + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index d37e9fd5be..641d96a824 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -26,6 +26,14 @@ When source evidence is used to authorize or update an individual recipient, an The digest preimage is the entire declared event object excluding **only** `eventDigest`, serialized as RFC 8785 canonical JSON UTF-8. `eventDigest` is `sha256:` plus 64 lowercase hexadecimal SHA-256 digits. Receivers reject duplicate properties, unknown/missing fields, noncanonical scope/counters, mismatched cutoff evidence, and a changed field paired with the original digest. Account stores the complete canonical event with the password mutation, token consumption, source generation/version and applicable local fence advance in one transaction. The separate Account-authenticated recipient snapshot binds this event to current recipient evidence; the event never creates gameplay admission. [Account API Contracts](./microservices/account-service/api-contracts.md) owns reset operation identity and exact-result retry. Other Account change types, issuer cutoffs and tenant billing changes require their own declared closed schemas before emission; this password-reset schema must not be aliased or fabricated for them. +#### Issuer Generation Source Event + +`account-auth-issuer-generation-event/v1` is the closed source schema for one Account-committed issuer-generation advance. Its required preimage fields are `schemaVersion` (exactly `account-auth-issuer-generation-event/v1`), `eventType` (exactly `ISSUER_GENERATION_ADVANCED`), `eventId`, `requestId`, `issuerId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `issuerAuthGeneration`, and `sourceVersion`; its sole additional wire field is `eventDigest`. `issuerId` is the exact configured Account JWT issuer identity, not an Account or tenant selector, and is never normalized or inferred. `sourceScope` is exactly `issuer/` and `outboxStreamKey` is exactly `account:auth-authority:v1:`. Request and event identities are nonempty immutable strings. The sequence, generation and source version are canonical positive decimal strings; consumers parse arbitrary precision. There are no optional fields, arrays, recipient tuples, recipient issuance fences, account/tenant IDs, cutoff objects or `null` placeholders. + +The digest preimage is the entire declared object excluding only `eventDigest`, serialized as RFC 8785 canonical JSON UTF-8. The digest uses lowercase `sha256:` plus 64 lowercase hexadecimal digits. Reject duplicate, unknown or missing properties, numeric/noncanonical counters, mismatched scope/stream and altered payload paired with the original digest. Account advances the exact issuer generation/source version and appends the complete event and checkpoint in one local transaction. This source operation does not rotate signing keys, change an individual Account fence, or authorize a recipient. [Account API Contracts](./microservices/account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback) owns its exact operation/retry identity and source readback. + +Issuer bootstrap readback requires a positive persisted issuer authority row and proved absence of committed events in that exact stream in the same fenced Account snapshot; a missing stream row alone is insufficient. Its checkpoint is then sequence zero with no event ID or digest, and grants no admission. Positive readback binds the current generation/source version to the exact latest immutable issuer event, payload/digest and stream checkpoint. Historical operation retry returns its original committed event rather than reapplying an advance; it is not current recipient authorization. The receiver still requires Account authentication and atomic projection/checkpoint installation. A local codec or unwired producer does not establish that authenticated handoff or complete projection proof. + ### Playtest Grant Admission Consequence Account's explicit grant record, bounded expiry, revision/request replay, tombstone, tenant-admin authority, and audited platform-admin break-glass mutation path are canonical in [Account API Contracts](./microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Authentication owns only the caller-bound consequence: private/playtest discovery, connect-token issuance, `PLAY`, reconnect, and continued gameplay require the current Account grant in addition to `ACTIVE` membership, entitlement, and exact routing evidence. Effective expiry or revocation is an immediate authority cutoff, not a grace period; Game Session consumes Account's bounded authority change and terminates affected bindings. A friendly scheduled ending uses the separate close-and-drain lifecycle before grant revocation. No JWT role, cached discovery result, or grant projection creates gameplay authority by itself. 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 ae3f2670c7..297e08f1b8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The issuer-generation source batch in [#2933](https://github.com/benhook1013/FireMUD/pull/2933) declares the closed `account-auth-issuer-generation-event/v1` schema at Authentication, with a shared strict codec and fixed/large-counter vectors. An unwired Account producer owns a short row-fenced transaction that advances the exact persisted issuer generation/source version and appends its immutable event/checkpoint together, then requires exact post-commit readback. Same-request recovery returns its original event after later advances; changed expected state, wrong issuer, absent source, contradictory checkpoint and counter overflow deny without enrollment or a second mutation. Seven unit and twelve PostgreSQL cases cover input/snapshot shape, concurrent retry, rollback and committed-but-unacknowledged recovery. The corrected combined Account/Common Platform/Game Session/TCP check passed 213 tasks, 68 executed and 145 up-to-date, including formatting, Checkstyle, SpotBugs and JaCoCo. Account executed 533 unit cases, including all seven producer cases; Common Platform's earlier same-code check executed 139 cases, including six new codec cases, with results reused by the combined gate. All 179 Account PostgreSQL cases compiled but skipped without Docker, including the twelve issuer cases. Game Session executed 1,813 unit, eighteen integration and one cross-service case, with 17/143/33 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen cross-service skips. All executed cases were clean. All seventeen association PostgreSQL cases, including the new pointer regression, compiled but skipped locally. Exact-head runner execution and full transport proof remain required. The local component is not an authenticated source handoff, signing-key rotation, delivered revocation or Game Session issuer projection; those implementations and their executed proof remain required. No recipient Account tuple/fence is fabricated for issuer-scoped source maintenance. Runtime activation and the ring mount remain denied. + +Exact preceding-head [CI 36952328785](https://github.com/benhook1013/FireMUD/actions/runs/36952328785) at `c5bebbf4d97cc08cefa0986faa69948102a75b45` executed all sixteen association and eight required password-reset PostgreSQL methods with no skips, failures or errors; the complete intended XML artifacts were retrieved and parsed. Its broader Game Session and Account-backed TCP setup failures share a concrete fixture cause: the baseline truncated runtime instances while retaining canonical demo/sandbox pointers, so the strict snapshot validator correctly rejected the dangling sandbox target before gameplay assertions. The corrected synthetic baseline preserves those pointers and reuses explicitly declared instances 1/2, rejecting tenant/owner identity conflicts and never reducing the generated-ID sequence. A new PostgreSQL case checks repeated baselines, pointer targets and unchanged immutable association receipts. This test-only correction does not guess a retained production association or weaken the snapshot guard; corrected-head database and broad transport execution remain separate proof gates. + The shared command-test Account server now requires and preserves the exact canonical tenant UUID across membership evidence, maps, streams, checkpoints and request echoes, rejecting malformed identifiers without evidence. Its six direct RPC tests executed without skips or failures. The retained demo command fixture declares one arbitrary UUID association for its private tenant key, captures and commits real local snapshot/association evidence, and checks the production read-only resolver; later baselines and restarted fixture objects must reuse the complete historical receipt. Three PostgreSQL composition cases cover registration/resolution, immutable retry after source changes, and unknown or contradictory mapping/configuration. Their synthetic Game Design approval is explicitly test-only, not authenticated owner handoff or live catalog proof. Local database execution and composed transport proof remain unavailable without Docker; runtime activation and the response-envelope ring mount remain denied. The current combined [#2933](https://github.com/benhook1013/FireMUD/pull/2933) absorbs the retained tenant-UUID consumer formerly packaged as #2935; separate Account-source and Game Session-consumer proof remains attributed below. Exact-head [CI 36947366507](https://github.com/benhook1013/FireMUD/actions/runs/36947366507) at `194eae43c6d10b2f5d476d7a65baae4ee3e44bc3` strictly executed all six password-reset producer and both required application cases once without skips, failures or errors. Game Session's component step executed four snapshot and eleven association cases cleanly, including both retained-key UUID lookup methods. These counts are strict job-log evidence: the Account artifact retained only the application XML, and the Game Session artifact missed its long XML filename. Class-bounded artifact globs correct that capture defect without changing suite/case requirements. The aggregate run failed, and the later broad Game Session task was canceled after cross-service assertions; full transport/admission proof remains open, not presumed inherited or fixed by these successful components. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java new file mode 100644 index 0000000000..961e7b6254 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java @@ -0,0 +1,573 @@ +package net.firedevops.firemud.accountservice.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired owner-local issuer-generation source mutation and readback. + * + *

This class is deliberately not a Spring component. Its caller must explicitly supply the + * configured issuer and dependencies; it does not add an endpoint, activate delivery, rotate a + * signing key, or establish authenticated consumer evidence. Each public operation owns a short + * writable READ_COMMITTED transaction and performs no network calls. + */ +public final class AccountIssuerAuthorityEventProducer { + private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final int MAX_ISSUER_ID_LENGTH = 512; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + + private final String exactIssuerId; + private final AuthorityScope issuerScope; + private final String sourceScope; + private final String outboxStreamKey; + private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthorityOutboxRepository outboxRepository; + private final DSLContext dsl; + private final TransactionTemplate ownerTransaction; + + public AccountIssuerAuthorityEventProducer( + String exactIssuerId, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + DSLContext dsl, + PlatformTransactionManager transactionManager) { + if (exactIssuerId == null + || exactIssuerId.isBlank() + || exactIssuerId.length() > MAX_ISSUER_ID_LENGTH) { + throw new IllegalArgumentException("Exact configured Account issuer ID is required"); + } + this.exactIssuerId = exactIssuerId; + this.issuerScope = AuthorityScope.issuer(exactIssuerId); + this.sourceScope = "issuer/" + exactIssuerId; + this.outboxStreamKey = AUTHORITY_STREAM_PREFIX + sourceScope; + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority-generation repository is required"); + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); + this.dsl = Objects.requireNonNull(dsl, "transaction-aware DSLContext is required"); + Objects.requireNonNull(transactionManager, "Account transaction manager is required"); + + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Advances the exact configured issuer source or recovers its original immutable event. + * + *

The request UUID is the stable operation identity within this exact issuer. The transaction + * first locks the persisted issuer row, then resolves the immutable request event before + * considering the caller's expected source state. A second, genuinely post-commit locked read + * must prove the same event before success is returned. If that read is unavailable, an exact + * retry recovers it without applying another advance. + */ + public IssuerGenerationAuthorityEvent advance( + String requestedIssuerId, + UUID requestId, + long expectedIssuerAuthGeneration, + long expectedSourceVersion) { + requireExactIssuer(requestedIssuerId); + requireRequestId(requestId); + if (expectedIssuerAuthGeneration <= 0L || expectedSourceVersion <= 0L) { + throw new IllegalArgumentException( + "Expected issuer generation and source version must be positive"); + } + requireNoAmbientTransaction(); + + IssuerGenerationAuthorityEvent transactionResult = + ownerTransaction.execute( + status -> + advanceInOwnerTransaction( + requestId, expectedIssuerAuthGeneration, expectedSourceVersion)); + if (transactionResult == null) { + throw new IllegalStateException("Issuer authority advance transaction returned no event"); + } + + IssuerGenerationAuthorityEvent committedResult = + readCommittedOperation(requestId, expectedIssuerAuthGeneration, expectedSourceVersion); + if (!sameEvent(transactionResult, committedResult)) { + throw new IllegalStateException( + "Post-commit issuer event readback differs from its transaction result"); + } + return committedResult; + } + + /** + * Reads current positive issuer source state and exact latest V33 checkpoint in one row-fenced + * snapshot. + */ + public IssuerAuthoritySnapshot readCurrent(String requestedIssuerId) { + requireExactIssuer(requestedIssuerId); + requireNoAmbientTransaction(); + IssuerAuthoritySnapshot snapshot = + ownerTransaction.execute(status -> readCurrentInTransaction()); + if (snapshot == null) { + throw new IllegalStateException("Issuer authority snapshot transaction returned no state"); + } + return snapshot; + } + + private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( + UUID requestId, long expectedGeneration, long expectedSourceVersion) { + ScopeState current = readLockedIssuerState(); + + // Resolve the immutable operation result first while the issuer row is held. This is the + // recovery path after a committed operation whose response or post-commit read was lost. + Optional prior = outboxRepository.findEvent(outboxStreamKey, requestId.toString()); + if (prior.isPresent()) { + IssuerGenerationAuthorityEvent historical = + verifyStoredEvent(prior.get(), requestId, expectedGeneration, expectedSourceVersion); + LatestEvidence currentHistory = requireCurrentHistoryMatches(current); + requireHistoricalEventIsRetained(prior.get(), current, currentHistory); + return historical; + } + + if (current.generation() != expectedGeneration + || current.sourceVersion() != expectedSourceVersion) { + throw new IllegalStateException("Issuer authority source compare-and-advance is stale"); + } + + long nextGeneration = incrementExact(expectedGeneration, "issuer generation"); + long nextSourceVersion = incrementExact(expectedSourceVersion, "issuer source version"); + LatestEvidence priorHistory = requireCurrentHistoryMatches(current); + long nextSequence = incrementExact(priorHistory.sequence(), "issuer outbox sequence"); + String requestText = requestId.toString(); + String eventId = EVENT_ID_PREFIX + requestText; + + ScopeState advanced = generationRepository.advance(current, null); + requireScopeState(advanced, nextGeneration, nextSourceVersion); + + Event appended = + outboxRepository.append( + outboxStreamKey, + requestText, + sequence -> + eventEvidence(requestText, eventId, sequence, nextGeneration, nextSourceVersion)); + if (appended.outboxSequence() != nextSequence) { + throw new IllegalStateException( + "Issuer authority outbox sequence did not advance exactly once"); + } + IssuerGenerationAuthorityEvent appendedEvent = + verifyStoredEvent(appended, requestId, expectedGeneration, expectedSourceVersion); + + // Prove the committed transaction's exact event, source row and checkpoint before allowing + // the transaction to commit. Any inconsistency escapes and rolls all three back together. + Event requestReadback = + outboxRepository + .findEvent(outboxStreamKey, requestText) + .orElseThrow( + () -> + new IllegalStateException( + "Issuer authority request event readback is missing")); + Event sequenceReadback = + outboxRepository + .findEvent(outboxStreamKey, nextSequence) + .orElseThrow( + () -> + new IllegalStateException( + "Issuer authority sequence event readback is missing")); + if (!appended.equals(requestReadback) || !appended.equals(sequenceReadback)) { + throw new IllegalStateException( + "Issuer authority immutable event readback differs from append"); + } + Checkpoint checkpoint = + outboxRepository + .readCheckpoint(outboxStreamKey) + .orElseThrow( + () -> new IllegalStateException("Issuer authority checkpoint readback is missing")); + requireCheckpointMatches(checkpoint, appended); + ScopeState sourceReadback = readLockedIssuerState(); + requireScopeState(sourceReadback, nextGeneration, nextSourceVersion); + LatestEvidence currentHistory = requireCurrentHistoryMatches(sourceReadback); + if (currentHistory.sequence() != nextSequence + || currentHistory.event().isEmpty() + || currentHistory.outboxEvent().isEmpty() + || !appended.equals(currentHistory.outboxEvent().orElseThrow())) { + throw new IllegalStateException( + "Issuer authority source and outbox readback differ from the advance"); + } + return appendedEvent; + } + + private IssuerGenerationAuthorityEvent readCommittedOperation( + UUID requestId, long expectedGeneration, long expectedSourceVersion) { + requireNoAmbientTransaction(); + IssuerGenerationAuthorityEvent event = + ownerTransaction.execute( + status -> { + ScopeState current = readLockedIssuerState(); + Event committed = + outboxRepository + .findEvent(outboxStreamKey, requestId.toString()) + .orElseThrow( + () -> + new IllegalStateException( + "Post-commit issuer authority request event is missing")); + IssuerGenerationAuthorityEvent verified = + verifyStoredEvent( + committed, requestId, expectedGeneration, expectedSourceVersion); + LatestEvidence currentHistory = requireCurrentHistoryMatches(current); + requireHistoricalEventIsRetained(committed, current, currentHistory); + if (committed.outboxSequence() > currentHistory.sequence()) { + throw new IllegalStateException( + "Post-commit issuer event is ahead of its checkpoint"); + } + return verified; + }); + if (event == null) { + throw new IllegalStateException("Post-commit issuer authority readback returned no event"); + } + return event; + } + + private IssuerAuthoritySnapshot readCurrentInTransaction() { + ScopeState current = readLockedIssuerState(); + LatestEvidence history = requireCurrentHistoryMatches(current); + return new IssuerAuthoritySnapshot( + exactIssuerId, + current.generation(), + current.sourceVersion(), + outboxStreamKey, + history.sequence(), + history.event()); + } + + private ScopeState readLockedIssuerState() { + ScopeState state = generationRepository.read(issuerScope); + if (state == null + || !issuerScope.equals(state.scope()) + || state.issuanceFence() != null + || state.generation() <= 0L + || state.sourceVersion() <= 0L) { + throw new IllegalStateException( + "Persisted Account issuer authority state is absent or malformed"); + } + return state; + } + + /** + * Validates the exact V33 checkpoint and latest event while the source row is locked. Sequence + * zero is returned only after counting the exact stream's events and proving the original source + * baseline; a missing V33 stream row by itself is not absence proof. + */ + private LatestEvidence requireCurrentHistoryMatches(ScopeState current) { + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR SHARE", + outboxStreamKey); + if (stream == null) { + Record eventCountReadback = + dsl.fetchOne( + "SELECT COUNT(*) AS event_count FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + outboxStreamKey); + Long eventCount = + eventCountReadback == null ? null : eventCountReadback.get("event_count", Long.class); + if (eventCount == null || eventCount < 0L) { + throw new IllegalStateException("Issuer authority retained event count is malformed"); + } + if (eventCount != 0L) { + throw new IllegalStateException( + "Issuer authority event history has no matching stream head"); + } + requireOriginalBaseline(current); + return LatestEvidence.empty(); + } + + Long headValue = stream.get("last_sequence", Long.class); + if (headValue == null || headValue < 0L) { + throw new IllegalStateException("Issuer authority stream head is malformed"); + } + if (headValue == 0L) { + throw new IllegalStateException( + "Committed zero-sequence issuer stream head contradicts the V33 checkpoint contract"); + } + + long headSequence = headValue; + Checkpoint checkpoint = + outboxRepository + .readCheckpoint(outboxStreamKey) + .orElseThrow( + () -> new IllegalStateException("Issuer authority positive checkpoint is missing")); + Event latest = + outboxRepository + .findEvent(outboxStreamKey, headSequence) + .orElseThrow( + () -> new IllegalStateException("Issuer authority checkpoint event is missing")); + requireCheckpointMatches(checkpoint, latest); + IssuerGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(latest); + if (!Long.toString(current.generation()).equals(verified.issuerAuthGeneration()) + || !Long.toString(current.sourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest issuer source event differs from current source counters"); + } + return new LatestEvidence(headSequence, Optional.of(verified), Optional.of(latest)); + } + + private void requireOriginalBaseline(ScopeState current) { + if (current.generation() != 1L || current.sourceVersion() != 1L) { + throw new IllegalStateException( + "Issuer sequence-zero readback requires the original positive 1/1 source baseline"); + } + } + + private void requireHistoricalEventIsRetained( + Event event, ScopeState current, LatestEvidence history) { + if (history.sequence() < event.outboxSequence()) { + throw new IllegalStateException("Historical issuer event is ahead of the current checkpoint"); + } + IssuerGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(event); + if (new java.math.BigInteger(verified.issuerAuthGeneration()) + .compareTo(java.math.BigInteger.valueOf(current.generation())) + > 0 + || new java.math.BigInteger(verified.sourceVersion()) + .compareTo(java.math.BigInteger.valueOf(current.sourceVersion())) + > 0) { + throw new IllegalStateException("Historical issuer event is ahead of current source state"); + } + } + + private EventEvidence eventEvidence( + String requestId, + String eventId, + long sequence, + long issuerAuthGeneration, + long sourceVersion) { + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + eventId, + "requestId", + requestId, + "issuerId", + exactIssuerId, + "sourceScope", + sourceScope, + "outboxStreamKey", + outboxStreamKey, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(issuerAuthGeneration), + "sourceVersion", + Long.toString(sourceVersion))); + return new EventEvidence(event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + } + + private IssuerGenerationAuthorityEvent verifyStoredEvent( + Event stored, UUID requestId, long expectedGeneration, long expectedSourceVersion) { + IssuerGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(stored); + String canonicalRequestId = requestId.toString(); + long resultingGeneration; + long resultingSourceVersion; + try { + resultingGeneration = Math.addExact(expectedGeneration, 1L); + resultingSourceVersion = Math.addExact(expectedSourceVersion, 1L); + } catch (ArithmeticException overflow) { + throw new AccountAuthorityOutboxRepository.IdempotencyConflictException( + "Issuer authority request identity was reused with different expected source state"); + } + if (!canonicalRequestId.equals(stored.requestId()) + || !canonicalRequestId.equals(verified.requestId()) + || !(EVENT_ID_PREFIX + canonicalRequestId).equals(stored.eventId()) + || !Long.toString(resultingGeneration).equals(verified.issuerAuthGeneration()) + || !Long.toString(resultingSourceVersion).equals(verified.sourceVersion())) { + throw new AccountAuthorityOutboxRepository.IdempotencyConflictException( + "Issuer authority request identity was reused with different expected source state"); + } + return verified; + } + + private IssuerGenerationAuthorityEvent verifyStoredEventWithoutRequest(Event stored) { + if (stored == null) { + throw new IllegalStateException("Issuer authority stored event is missing"); + } + IssuerGenerationAuthorityEvent verified = + IssuerGenerationAuthorityEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + if (!MessageDigest.isEqual(stored.payload(), verified.canonicalJsonUtf8()) + || !outboxStreamKey.equals(stored.outboxStreamKey()) + || !sourceScope.equals(verified.sourceScope()) + || !outboxStreamKey.equals(verified.outboxStreamKey()) + || !exactIssuerId.equals(verified.issuerId()) + || !stored.requestId().equals(verified.requestId()) + || !stored.eventId().equals(verified.eventId()) + || !stored.eventDigest().equals(verified.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(verified.outboxSequence()) + || !(EVENT_ID_PREFIX + stored.requestId()).equals(stored.eventId())) { + throw new IllegalStateException( + "Issuer authority stored event payload or database columns contradict"); + } + requireCanonicalStoredRequestId(stored.requestId()); + return verified; + } + + private void requireCanonicalStoredRequestId(String requestId) { + try { + UUID parsed = UUID.fromString(requestId); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(requestId)) { + throw new IllegalStateException("Issuer authority stored request ID is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Issuer authority stored request ID is not a canonical UUID", malformed); + } + } + + private void requireScopeState(ScopeState state, long generation, long sourceVersion) { + if (state == null + || !issuerScope.equals(state.scope()) + || state.issuanceFence() != null + || state.generation() != generation + || state.sourceVersion() != sourceVersion) { + throw new IllegalStateException( + "Persisted Account issuer source did not match its expected advance"); + } + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { + if (checkpoint == null + || event == null + || !outboxStreamKey.equals(checkpoint.outboxStreamKey()) + || !checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException( + "Issuer authority checkpoint differs from its immutable event"); + } + } + + private void requireExactIssuer(String requestedIssuerId) { + if (!exactIssuerId.equals(requestedIssuerId)) { + throw new IllegalArgumentException( + "Issuer authority request must name the exact configured issuer"); + } + } + + private void requireRequestId(UUID requestId) { + if (requestId == null || new UUID(0L, 0L).equals(requestId)) { + throw new IllegalArgumentException( + "Issuer authority request ID must be a canonical non-nil UUID"); + } + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer authority producer must own its Account transaction without an ambient transaction"); + } + } + + private static long incrementExact(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account " + field + " is exhausted", overflow); + } + } + + private static boolean sameEvent( + IssuerGenerationAuthorityEvent first, IssuerGenerationAuthorityEvent second) { + return first != null + && second != null + && first.eventId().equals(second.eventId()) + && first.requestId().equals(second.requestId()) + && first.issuerId().equals(second.issuerId()) + && first.sourceScope().equals(second.sourceScope()) + && first.outboxStreamKey().equals(second.outboxStreamKey()) + && first.outboxSequence().equals(second.outboxSequence()) + && first.issuerAuthGeneration().equals(second.issuerAuthGeneration()) + && first.sourceVersion().equals(second.sourceVersion()) + && first.eventDigest().equals(second.eventDigest()) + && MessageDigest.isEqual(first.canonicalJsonUtf8(), second.canonicalJsonUtf8()); + } + + /** Current exact source evidence; the event is omitted when the proven checkpoint is zero. */ + public record IssuerAuthoritySnapshot( + String issuerId, + long issuerAuthGeneration, + long sourceVersion, + String outboxStreamKey, + long outboxSequence, + Optional latestEvent) { + public IssuerAuthoritySnapshot { + if (issuerId == null + || issuerId.isBlank() + || issuerAuthGeneration <= 0L + || sourceVersion <= 0L + || outboxStreamKey == null + || outboxSequence < 0L) { + throw new IllegalArgumentException("Issuer authority snapshot fields are incomplete"); + } + String expectedSourceScope = "issuer/" + issuerId; + String expectedStreamKey = AUTHORITY_STREAM_PREFIX + expectedSourceScope; + if (!expectedStreamKey.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Issuer authority snapshot stream does not bind its issuer"); + } + latestEvent = Objects.requireNonNull(latestEvent, "issuer latest event optional is required"); + if ((outboxSequence == 0L) != latestEvent.isEmpty()) { + throw new IllegalArgumentException("Issuer sequence-zero snapshot must omit its event"); + } + if (outboxSequence == 0L && (issuerAuthGeneration != 1L || sourceVersion != 1L)) { + throw new IllegalArgumentException( + "Issuer sequence-zero snapshot requires the positive 1/1 baseline"); + } + latestEvent.ifPresent( + event -> { + if (!issuerId.equals(event.issuerId()) + || !expectedSourceScope.equals(event.sourceScope()) + || !outboxStreamKey.equals(event.outboxStreamKey()) + || !Long.toString(outboxSequence).equals(event.outboxSequence()) + || !Long.toString(issuerAuthGeneration).equals(event.issuerAuthGeneration()) + || !Long.toString(sourceVersion).equals(event.sourceVersion())) { + throw new IllegalArgumentException( + "Issuer authority snapshot event differs from its checkpoint"); + } + }); + } + } + + private record LatestEvidence( + long sequence, Optional event, Optional outboxEvent) { + private LatestEvidence { + if (sequence < 0L) { + throw new IllegalArgumentException("Issuer authority history sequence cannot be negative"); + } + event = Objects.requireNonNull(event, "issuer history event optional is required"); + outboxEvent = Objects.requireNonNull(outboxEvent, "issuer outbox event optional is required"); + if ((sequence == 0L) != event.isEmpty() || event.isEmpty() != outboxEvent.isEmpty()) { + throw new IllegalArgumentException("Issuer authority history evidence is incomplete"); + } + } + + private static LatestEvidence empty() { + return new LatestEvidence(0L, Optional.empty(), Optional.empty()); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java new file mode 100644 index 0000000000..3ff01479e9 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -0,0 +1,586 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class IssuerAuthorityProducerPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "issuer_authority_source_proof"; + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void atomicallyAdvancesSourceAndEventAndReadsBackExactCheckpoint() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot baseline = + fixture.producer().readCurrent(ISSUER_ID); + assertThat(baseline.issuerAuthGeneration()).isEqualTo(1L); + assertThat(baseline.sourceVersion()).isEqualTo(1L); + assertThat(baseline.outboxSequence()).isZero(); + assertThat(baseline.latestEvent()).isEmpty(); + + UUID requestId = UUID.randomUUID(); + IssuerGenerationAuthorityEvent event = fixture.producer().advance(ISSUER_ID, requestId, 1L, 1L); + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot current = + fixture.producer().readCurrent(ISSUER_ID); + + assertThat(event.eventId()).isEqualTo(EVENT_ID_PREFIX + requestId); + assertThat(event.requestId()).isEqualTo(requestId.toString()); + assertThat(event.issuerId()).isEqualTo(ISSUER_ID); + assertThat(event.sourceScope()).isEqualTo("issuer/" + ISSUER_ID); + assertThat(event.outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.issuerAuthGeneration()).isEqualTo("2"); + assertThat(event.sourceVersion()).isEqualTo("2"); + assertThat(event.eventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(current.issuerAuthGeneration()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.outboxSequence()).isEqualTo(1L); + assertThat(current.latestEvent()).isPresent(); + assertSameEvent(event, current.latestEvent().orElseThrow()); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(1L); + } + + @Test + void exactRetryRecoversLostResponseAndOriginalEventAfterLaterAdvance() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + UUID firstRequest = UUID.randomUUID(); + IssuerGenerationAuthorityEvent first = + fixture.producer().advance(ISSUER_ID, firstRequest, 1L, 1L); + IssuerGenerationAuthorityEvent exactRetry = + fixture.producer().advance(ISSUER_ID, firstRequest, 1L, 1L); + assertSameEvent(first, exactRetry); + + UUID secondRequest = UUID.randomUUID(); + IssuerGenerationAuthorityEvent second = + fixture.producer().advance(ISSUER_ID, secondRequest, 2L, 2L); + IssuerGenerationAuthorityEvent historicalRetry = + fixture.producer().advance(ISSUER_ID, firstRequest, 1L, 1L); + assertSameEvent(first, historicalRetry); + assertThat(second.outboxSequence()).isEqualTo("2"); + assertThat(fixture.producer().readCurrent(ISSUER_ID).latestEvent()).isPresent(); + assertSameEvent(second, fixture.producer().readCurrent(ISSUER_ID).latestEvent().orElseThrow()); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(2L); + } + + @Test + void concurrentExactRequestSerializesAndCommitsOneSourceEvent() throws Exception { + Fixture fixture = newFixture(); + seedIssuer(fixture); + UUID requestId = UUID.randomUUID(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var first = executor.submit(() -> concurrentAdvance(fixture, requestId, ready, start)); + var second = executor.submit(() -> concurrentAdvance(fixture, requestId, ready, start)); + assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + IssuerGenerationAuthorityEvent firstEvent = first.get(45, TimeUnit.SECONDS); + IssuerGenerationAuthorityEvent secondEvent = second.get(45, TimeUnit.SECONDS); + assertSameEvent(firstEvent, secondEvent); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThat(readAuthority(fixture).generation()).isEqualTo(2L); + assertThat(readAuthority(fixture).sourceVersion()).isEqualTo(2L); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(1L); + assertThat(countStreams(fixture)).isEqualTo(1L); + } + + @Test + void changedExpectedStateForSameRequestConflictsWithoutMutation() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + UUID requestId = UUID.randomUUID(); + fixture.producer().advance(ISSUER_ID, requestId, 1L, 1L); + StoredState committed = snapshot(fixture); + + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, requestId, 2L, 2L)) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + + assertThat(snapshot(fixture)).isEqualTo(committed); + } + + @Test + void wrongIssuerStaleRequestAndMissingSourceFailWithoutEnrollmentOrMutation() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + StoredState baseline = snapshot(fixture); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + fixture.producer().advance("https://other.example.test/issuer", requestId, 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, new UUID(0L, 0L), 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, requestId, 2L, 2L)) + .isInstanceOf(IllegalStateException.class); + assertThat(snapshot(fixture)).isEqualTo(baseline); + + Fixture missing = newFixture(); + assertThatThrownBy(() -> missing.producer().readCurrent(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("generation is missing"); + assertThatThrownBy(() -> missing.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalStateException.class); + assertThat(countStreams(missing)).isZero(); + assertThat(countEvents(missing, STREAM_KEY)).isZero(); + } + + @Test + void sequenceZeroRequiresOriginalPositiveBaselineAndNoContradictoryStreamOrHistory() { + Fixture baseline = newFixture(); + seedIssuer(baseline); + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot zero = + baseline.producer().readCurrent(ISSUER_ID); + assertThat(zero.issuerAuthGeneration()).isEqualTo(1L); + assertThat(zero.sourceVersion()).isEqualTo(1L); + assertThat(zero.outboxSequence()).isZero(); + assertThat(zero.latestEvent()).isEmpty(); + + Fixture advancedWithoutEvents = newFixture(); + seedIssuer(advancedWithoutEvents); + forceIssuerCounters(advancedWithoutEvents, 2L, 2L); + assertThatThrownBy(() -> advancedWithoutEvents.producer().readCurrent(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original positive 1/1"); + + Fixture contradictoryHead = newFixture(); + seedIssuer(contradictoryHead); + contradictoryHead + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_streams " + + "DISABLE TRIGGER account_authority_outbox_stream_consistent"); + contradictoryHead + .setupDsl() + .execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 1)", + STREAM_KEY); + contradictoryHead + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_streams " + + "ENABLE TRIGGER account_authority_outbox_stream_consistent"); + assertThatThrownBy(() -> contradictoryHead.producer().readCurrent(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("checkpoint has no matching event evidence"); + + Fixture committedZeroHead = newFixture(); + seedIssuer(committedZeroHead); + committedZeroHead + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_streams " + + "DISABLE TRIGGER account_authority_outbox_stream_consistent"); + committedZeroHead + .setupDsl() + .execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0)", + STREAM_KEY); + committedZeroHead + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_streams " + + "ENABLE TRIGGER account_authority_outbox_stream_consistent"); + assertThatThrownBy(() -> committedZeroHead.producer().readCurrent(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Committed zero-sequence issuer stream head"); + } + + @Test + void positiveReadbackRejectsSourceCountersThatDifferFromLatestEvent() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L); + forceIssuerCounters(fixture, 3L, 3L); + + assertThatThrownBy(() -> fixture.producer().readCurrent(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Latest issuer source event differs"); + } + + @Test + void positiveReadbackUsesExplicitLatestEventCountersInsteadOfDerivingThemFromSequence() { + Fixture fixture = newFixture(); + // Seed an already-positive V31 source row as fixture state; this is not migration provenance + // proof. + fixture + .setupDsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('ISSUER', ?, NULL, NULL, 3, 7)", + ISSUER_ID); + transaction( + fixture.transaction(), + () -> { + ScopeState baseline = fixture.generations().read(AuthorityScope.issuer(ISSUER_ID)); + ScopeState advanced = fixture.generations().advance(baseline, null); + assertThat(advanced.generation()).isEqualTo(4L); + assertThat(advanced.sourceVersion()).isEqualTo(8L); + appendSeedEvent(fixture, UUID.randomUUID(), 4L, 8L); + return null; + }); + + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot snapshot = + fixture.producer().readCurrent(ISSUER_ID); + assertThat(snapshot.issuerAuthGeneration()).isEqualTo(4L); + assertThat(snapshot.sourceVersion()).isEqualTo(8L); + assertThat(snapshot.outboxSequence()).isEqualTo(1L); + assertThat(snapshot.latestEvent()).isPresent(); + IssuerGenerationAuthorityEvent latest = snapshot.latestEvent().orElseThrow(); + assertThat(latest.outboxSequence()).isEqualTo("1"); + assertThat(latest.issuerAuthGeneration()).isEqualTo("4"); + assertThat(latest.sourceVersion()).isEqualTo("8"); + } + + @Test + void appendFailureRollsBackSourceAndOutboxTogether() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "ADD CONSTRAINT reject_issuer_source_event " + + "CHECK (event_id NOT LIKE 'account-issuer-authority-event-v1:%')"); + + assertThatThrownBy(() -> fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(RuntimeException.class); + + assertThat(readAuthority(fixture).generation()).isEqualTo(1L); + assertThat(readAuthority(fixture).sourceVersion()).isEqualTo(1L); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + assertThat(countStreams(fixture)).isZero(); + } + + @Test + void transactionLocalEventReadbackFailureRollsBackTheAdvance() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + AccountAuthorityOutboxRepository hideSecondRequestRead = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()) { + private final AtomicInteger requestLookups = new AtomicInteger(); + + @Override + public Optional findEvent(String streamKey, String requestId) { + if (requestLookups.incrementAndGet() >= 2) { + return Optional.empty(); + } + return super.findEvent(streamKey, requestId); + } + }; + AccountIssuerAuthorityEventProducer producer = fixture.producer(hideSecondRequestRead); + + assertThatThrownBy(() -> producer.advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request event readback is missing"); + + assertThat(readAuthority(fixture).generation()).isEqualTo(1L); + assertThat(readAuthority(fixture).sourceVersion()).isEqualTo(1L); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + assertThat(countStreams(fixture)).isZero(); + } + + @Test + void unavailablePostCommitReadDoesNotUndoAndExactRetryRecoversWithoutAdvancingAgain() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + AtomicInteger requestLookups = new AtomicInteger(); + AccountAuthorityOutboxRepository hidePostCommitRead = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, String requestId) { + if (requestLookups.incrementAndGet() == 3) { + return Optional.empty(); + } + return super.findEvent(streamKey, requestId); + } + }; + UUID requestId = UUID.randomUUID(); + AccountIssuerAuthorityEventProducer firstAttempt = fixture.producer(hidePostCommitRead); + + assertThatThrownBy(() -> firstAttempt.advance(ISSUER_ID, requestId, 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Post-commit issuer authority request event is missing"); + + assertThat(readAuthority(fixture).generation()).isEqualTo(2L); + assertThat(readAuthority(fixture).sourceVersion()).isEqualTo(2L); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(1L); + IssuerGenerationAuthorityEvent recovered = + fixture.producer().advance(ISSUER_ID, requestId, 1L, 1L); + assertThat(recovered.eventId()).isEqualTo(EVENT_ID_PREFIX + requestId); + assertThat(readAuthority(fixture).generation()).isEqualTo(2L); + assertThat(readAuthority(fixture).sourceVersion()).isEqualTo(2L); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(1L); + } + + @Test + void generationAndSourceVersionOverflowFailBeforeAnyMutation() { + Fixture generationOverflow = newFixture(); + seedIssuer(generationOverflow); + forceIssuerCounters(generationOverflow, Long.MAX_VALUE, 1L); + assertThatThrownBy( + () -> + generationOverflow + .producer() + .advance(ISSUER_ID, UUID.randomUUID(), Long.MAX_VALUE, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("issuer generation is exhausted"); + assertCountersAndOutbox(generationOverflow, Long.MAX_VALUE, 1L); + + Fixture sourceVersionOverflow = newFixture(); + seedIssuer(sourceVersionOverflow); + forceIssuerCounters(sourceVersionOverflow, 1L, Long.MAX_VALUE); + assertThatThrownBy( + () -> + sourceVersionOverflow + .producer() + .advance(ISSUER_ID, UUID.randomUUID(), 1L, Long.MAX_VALUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("issuer source version is exhausted"); + assertCountersAndOutbox(sourceVersionOverflow, 1L, Long.MAX_VALUE); + } + + private IssuerGenerationAuthorityEvent concurrentAdvance( + Fixture fixture, UUID requestId, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return fixture.producer().advance(ISSUER_ID, requestId, 1L, 1L); + } + + private Fixture newFixture() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + return new Fixture( + setupDsl, transactionDsl, transactionManager, transaction, generations, outbox); + } + + private void seedIssuer(Fixture fixture) { + transaction( + fixture.transaction(), + () -> { + fixture.generations().initializeIssuerIfAbsent(ISSUER_ID); + return null; + }); + } + + private void appendSeedEvent( + Fixture fixture, UUID requestId, long issuerGeneration, long sourceVersion) { + String requestText = requestId.toString(); + String eventId = EVENT_ID_PREFIX + requestText; + fixture + .outbox() + .append( + STREAM_KEY, + requestText, + sequence -> { + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + eventId, + "requestId", + requestText, + "issuerId", + ISSUER_ID, + "sourceScope", + "issuer/" + ISSUER_ID, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(issuerGeneration), + "sourceVersion", + Long.toString(sourceVersion))); + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + } + + private void forceIssuerCounters(Fixture fixture, long generation, long sourceVersion) { + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_generations " + + "DISABLE TRIGGER account_authority_generations_monotonic"); + fixture + .setupDsl() + .execute( + "UPDATE account_authority_generations SET generation = ?, source_version = ? " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + generation, + sourceVersion, + ISSUER_ID); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_generations " + + "ENABLE TRIGGER account_authority_generations_monotonic"); + } + + private void assertCountersAndOutbox(Fixture fixture, long generation, long sourceVersion) { + ScopeState authority = readAuthority(fixture); + assertThat(authority.generation()).isEqualTo(generation); + assertThat(authority.sourceVersion()).isEqualTo(sourceVersion); + assertThat(countEvents(fixture, STREAM_KEY)).isZero(); + assertThat(countStreams(fixture)).isZero(); + } + + private ScopeState readAuthority(Fixture fixture) { + return transaction( + fixture.transaction(), () -> fixture.generations().read(AuthorityScope.issuer(ISSUER_ID))); + } + + private StoredState snapshot(Fixture fixture) { + ScopeState authority = readAuthority(fixture); + return new StoredState( + authority.generation(), + authority.sourceVersion(), + countEvents(fixture, STREAM_KEY), + countStreams(fixture)); + } + + private long countEvents(Fixture fixture, String streamKey) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class), + "Issuer event count readback is missing"); + } + + private long countStreams(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery("SELECT COUNT(*) FROM account_authority_outbox_streams") + .fetchOne(0, Long.class), + "Issuer stream count readback is missing"); + } + + private void assertSameEvent( + IssuerGenerationAuthorityEvent expected, IssuerGenerationAuthorityEvent actual) { + assertThat(actual.eventId()).isEqualTo(expected.eventId()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.sourceScope()).isEqualTo(expected.sourceScope()); + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.issuerAuthGeneration()).isEqualTo(expected.issuerAuthGeneration()); + assertThat(actual.sourceVersion()).isEqualTo(expected.sourceVersion()); + assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); + assertThat(actual.canonicalJsonUtf8()).containsExactly(expected.canonicalJsonUtf8()); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent issuer authority barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent issuer authority proof was interrupted", interrupted); + } + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + DSLContext setupDsl, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transaction, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + private AccountIssuerAuthorityEventProducer producer() { + return producer(outbox); + } + + private AccountIssuerAuthorityEventProducer producer( + AccountAuthorityOutboxRepository outboxOverride) { + return new AccountIssuerAuthorityEventProducer( + ISSUER_ID, generations, outboxOverride, transactionDsl, transactionManager); + } + } + + private record StoredState( + long generation, long sourceVersion, long eventCount, long streamCount) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java new file mode 100644 index 0000000000..133c56a382 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java @@ -0,0 +1,247 @@ +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.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountIssuerAuthorityEventProducerTest { + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String OTHER_ISSUER_ID = "https://other.example.test/issuer"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + + @Test + void requestedIssuerMismatchIsRejectedBeforeDatabaseOrTransactionManagerInteraction() { + Collaborators collaborators = new Collaborators(); + AccountIssuerAuthorityEventProducer producer = newProducer(ISSUER_ID, collaborators); + + assertThatThrownBy(() -> producer.advance(OTHER_ISSUER_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact configured issuer"); + assertThatThrownBy(() -> producer.readCurrent(OTHER_ISSUER_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact configured issuer"); + + collaborators.verifyUnused(); + } + + @Test + void nilRequestAndNonpositiveExpectedCountersAreRejectedBeforePersistence() { + Collaborators collaborators = new Collaborators(); + AccountIssuerAuthorityEventProducer producer = newProducer(ISSUER_ID, collaborators); + + assertThatThrownBy(() -> producer.advance(ISSUER_ID, new UUID(0L, 0L), 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy(() -> producer.advance(ISSUER_ID, UUID.randomUUID(), 0L, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + assertThatThrownBy(() -> producer.advance(ISSUER_ID, UUID.randomUUID(), 1L, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + + collaborators.verifyUnused(); + } + + @Test + void missingConstructorCollaboratorsAreRejectedWithoutCallingOtherCollaborators() { + Collaborators collaborators = new Collaborators(); + + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer( + ISSUER_ID, + null, + collaborators.outboxRepository(), + collaborators.dsl(), + collaborators.transactionManager())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("authority-generation repository"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer( + ISSUER_ID, + collaborators.generationRepository(), + null, + collaborators.dsl(), + collaborators.transactionManager())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("authority outbox repository"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer( + ISSUER_ID, + collaborators.generationRepository(), + collaborators.outboxRepository(), + null, + collaborators.transactionManager())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("transaction-aware DSLContext"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer( + ISSUER_ID, + collaborators.generationRepository(), + collaborators.outboxRepository(), + collaborators.dsl(), + null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account transaction manager"); + + collaborators.verifyUnused(); + } + + @Test + void ambientActualTransactionIsRejectedAndThreadStateIsRestored() { + Collaborators collaborators = new Collaborators(); + AccountIssuerAuthorityEventProducer producer = newProducer(ISSUER_ID, collaborators); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy(() -> producer.readCurrent(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + assertThatThrownBy(() -> producer.advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + collaborators.verifyUnused(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void sequenceZeroSnapshotContainsOnlyProvenBaselineAndEmptyEventOptional() { + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot snapshot = + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty()); + + assertThat(snapshot.latestEvent()).isEmpty(); + assertThat(snapshot.outboxSequence()).isZero(); + } + + @Test + void sequenceZeroSnapshotRejectsWrongIssuerStreamAndUnprovenCounters() { + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, + 1L, + 1L, + "account:auth-authority:v1:issuer/" + OTHER_ISSUER_ID, + 0L, + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not bind its issuer"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 2L, 1L, STREAM_KEY, 0L, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive 1/1 baseline"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 1L, 2L, STREAM_KEY, 0L, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive 1/1 baseline"); + } + + @Test + void positiveSnapshotRejectsMissingOrMismatchedLatestEvent() { + UUID requestId = UUID.randomUUID(); + IssuerGenerationAuthorityEvent matchingEvent = event(ISSUER_ID, requestId, 1L, 2L, 2L); + IssuerGenerationAuthorityEvent wrongCounterEvent = + event(ISSUER_ID, UUID.randomUUID(), 1L, 2L, 3L); + + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 2L, 2L, STREAM_KEY, 1L, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must omit its event"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 2L, 2L, STREAM_KEY, 1L, Optional.of(wrongCounterEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from its checkpoint"); + + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot validShape = + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 2L, 2L, STREAM_KEY, 1L, Optional.of(matchingEvent)); + assertThat(validShape.latestEvent()).isPresent(); + assertThat(validShape.latestEvent().orElseThrow()).isSameAs(matchingEvent); + } + + private AccountIssuerAuthorityEventProducer newProducer( + String issuerId, Collaborators collaborators) { + return new AccountIssuerAuthorityEventProducer( + issuerId, + collaborators.generationRepository(), + collaborators.outboxRepository(), + collaborators.dsl(), + collaborators.transactionManager()); + } + + private IssuerGenerationAuthorityEvent event( + String issuerId, UUID requestId, long sequence, long issuerGeneration, long sourceVersion) { + String requestText = requestId.toString(); + String sourceScope = "issuer/" + issuerId; + String streamKey = "account:auth-authority:v1:" + sourceScope; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + requestText, + "requestId", + requestText, + "issuerId", + issuerId, + "sourceScope", + sourceScope, + "outboxStreamKey", + streamKey, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(issuerGeneration), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private record Collaborators( + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + DSLContext dsl, + PlatformTransactionManager transactionManager) { + private Collaborators() { + this( + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class), + mock(DSLContext.class), + mock(PlatformTransactionManager.class)); + } + + private void verifyUnused() { + verifyNoInteractions(generationRepository, outboxRepository, dsl, transactionManager); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java new file mode 100644 index 0000000000..257c34bef4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account issuer-generation authority events. */ +public final class IssuerGenerationAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-issuer-generation-event/v1"; + public static final String EVENT_TYPE = "ISSUER_GENERATION_ADVANCED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "issuerId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "issuerAuthGeneration", + "sourceVersion"); + private static final Set WIRE_FIELDS; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private IssuerGenerationAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static IssuerGenerationAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static IssuerGenerationAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static IssuerGenerationAuthorityEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static IssuerGenerationAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + requireNonEmptyText(event, "eventId", "event"); + requireNonEmptyText(event, "requestId", "event"); + + String issuerId = requireNonBlankText(event, "issuerId", "event"); + String sourceScope = "issuer/" + issuerId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + requirePositiveDecimal(event, "outboxSequence", "event"); + requirePositiveDecimal(event, "issuerAuthGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + } + + private static IssuerGenerationAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + return new IssuerGenerationAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("issuerId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("issuerAuthGeneration").textValue(), + wire.path("sourceVersion").textValue(), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireNonEmptyText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isEmpty()) { + throw invalid(path + "." + field, "must be nonempty"); + } + return value; + } + + private static String requireNonBlankText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isBlank()) { + throw invalid(path + "." + field, "must be nonblank"); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed issuer-generation event evidence. */ + public static final class IssuerGenerationAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String issuerId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String issuerAuthGeneration; + private final String sourceVersion; + private final String eventDigest; + private final String canonicalJson; + + private IssuerGenerationAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String issuerId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String issuerAuthGeneration, + String sourceVersion, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.issuerId = issuerId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.issuerAuthGeneration = issuerAuthGeneration; + this.sourceVersion = sourceVersion; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String issuerId() { + return issuerId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String issuerAuthGeneration() { + return issuerAuthGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json new file mode 100644 index 0000000000..898dd32a2e --- /dev/null +++ b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json @@ -0,0 +1,126 @@ +{ + "schemaVersion": "account-auth-issuer-generation-event-vectors/v1", + "validEvents": [ + { + "name": "issuer-generation-advance", + "event": { + "schemaVersion": "account-auth-issuer-generation-event/v1", + "eventType": "ISSUER_GENERATION_ADVANCED", + "eventId": "event-issuer-generation-001", + "requestId": "request-issuer-generation-001", + "issuerId": "https://Auth.FireMUD.example/issuer", + "sourceScope": "issuer/https://Auth.FireMUD.example/issuer", + "outboxStreamKey": "account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer", + "outboxSequence": "7", + "issuerAuthGeneration": "5", + "sourceVersion": "6", + "eventDigest": "sha256:df88f7ee54a9f24102b6fbecc5a93595091e2d6a1fc7fca8ba2d8bbbc08cb735" + }, + "expectedEventDigest": "sha256:df88f7ee54a9f24102b6fbecc5a93595091e2d6a1fc7fca8ba2d8bbbc08cb735", + "expectedCanonicalJson": "{\"eventDigest\":\"sha256:df88f7ee54a9f24102b6fbecc5a93595091e2d6a1fc7fca8ba2d8bbbc08cb735\",\"eventId\":\"event-issuer-generation-001\",\"eventType\":\"ISSUER_GENERATION_ADVANCED\",\"issuerAuthGeneration\":\"5\",\"issuerId\":\"https://Auth.FireMUD.example/issuer\",\"outboxSequence\":\"7\",\"outboxStreamKey\":\"account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer\",\"requestId\":\"request-issuer-generation-001\",\"schemaVersion\":\"account-auth-issuer-generation-event/v1\",\"sourceScope\":\"issuer/https://Auth.FireMUD.example/issuer\",\"sourceVersion\":\"6\"}" + }, + { + "name": "arbitrary-precision-counters", + "event": { + "schemaVersion": "account-auth-issuer-generation-event/v1", + "eventType": "ISSUER_GENERATION_ADVANCED", + "eventId": "event-issuer-generation-large", + "requestId": "request-issuer-generation-large", + "issuerId": "https://Auth.FireMUD.example/issuer", + "sourceScope": "issuer/https://Auth.FireMUD.example/issuer", + "outboxStreamKey": "account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer", + "outboxSequence": "18446744073709551616000000000000000001", + "issuerAuthGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "eventDigest": "sha256:98b9c742c3267d4db283196c1d80865c3ab9227df08c6efd8c7025d46c79ee5c" + }, + "expectedEventDigest": "sha256:98b9c742c3267d4db283196c1d80865c3ab9227df08c6efd8c7025d46c79ee5c", + "expectedCanonicalJson": "{\"eventDigest\":\"sha256:98b9c742c3267d4db283196c1d80865c3ab9227df08c6efd8c7025d46c79ee5c\",\"eventId\":\"event-issuer-generation-large\",\"eventType\":\"ISSUER_GENERATION_ADVANCED\",\"issuerAuthGeneration\":\"92233720368547758081234567890123456789\",\"issuerId\":\"https://Auth.FireMUD.example/issuer\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer\",\"requestId\":\"request-issuer-generation-large\",\"schemaVersion\":\"account-auth-issuer-generation-event/v1\",\"sourceScope\":\"issuer/https://Auth.FireMUD.example/issuer\",\"sourceVersion\":\"90071992547409931234567890123456789\"}" + } + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "sourceScope", + "schemaVersion", + "requestId", + "outboxStreamKey", + "outboxSequence", + "issuerId", + "issuerAuthGeneration", + "eventType", + "eventId", + "eventDigest" + ], + "changedDeclaredFieldMutations": [ + { + "name": "schema-version", + "sealValid": false, + "changes": {"schemaVersion": "account-auth-issuer-generation-event/v2"} + }, + { + "name": "event-type", + "sealValid": false, + "changes": {"eventType": "ISSUER_GENERATION_RESET"} + }, + { + "name": "event-id", + "sealValid": true, + "changes": {"eventId": "event-issuer-generation-changed"} + }, + { + "name": "request-id", + "sealValid": true, + "changes": {"requestId": "request-issuer-generation-changed"} + }, + { + "name": "issuer-id-preserves-exact-spelling", + "sealValid": true, + "changes": { + "issuerId": "https://auth.firemud.example/issuer", + "sourceScope": "issuer/https://auth.firemud.example/issuer", + "outboxStreamKey": "account:auth-authority:v1:issuer/https://auth.firemud.example/issuer" + } + }, + { + "name": "source-scope", + "sealValid": false, + "changes": {"sourceScope": "issuer/https://other.firemud.example/issuer"} + }, + { + "name": "outbox-stream-key", + "sealValid": false, + "changes": {"outboxStreamKey": "account:auth-authority:v1:issuer/https://other.firemud.example/issuer"} + }, + { + "name": "outbox-sequence", + "sealValid": true, + "changes": {"outboxSequence": "8"} + }, + { + "name": "issuer-auth-generation", + "sealValid": true, + "changes": {"issuerAuthGeneration": "6"} + }, + { + "name": "source-version", + "sealValid": true, + "changes": {"sourceVersion": "7"} + } + ], + "invalidMutations": [ + {"name": "missing-required-source-version", "op": "remove", "path": "/sourceVersion"}, + {"name": "unknown-top-level-property", "op": "add", "path": "/unexpected", "value": true}, + {"name": "null-issuer", "op": "replace", "path": "/issuerId", "value": null}, + {"name": "wrong-type-sequence", "op": "replace", "path": "/outboxSequence", "value": 7}, + {"name": "array-issuer", "op": "replace", "path": "/issuerId", "value": ["https://Auth.FireMUD.example/issuer"]}, + {"name": "blank-issuer", "op": "replace", "path": "/issuerId", "value": " \t"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "empty-request-id", "op": "replace", "path": "/requestId", "value": ""}, + {"name": "zero-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-generation", "op": "replace", "path": "/issuerAuthGeneration", "value": "05"}, + {"name": "negative-source-version", "op": "replace", "path": "/sourceVersion", "value": "-1"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "issuer/https://other.firemud.example/issuer"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:issuer/https://other.firemud.example/issuer"}, + {"name": "invalid-digest", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..830246b21f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class IssuerGenerationAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + IssuerGenerationAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-issuer-generation-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + IssuerGenerationAuthorityEvent verified = + IssuerGenerationAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + Map wireMap = JSON.convertValue(wireEvent, new TypeReference<>() {}); + assertThat(IssuerGenerationAuthorityEventV1Codec.verify(wireMap).canonicalJson()) + .isEqualTo(vector.path("expectedCanonicalJson").asText()); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + IssuerGenerationAuthorityEvent sealed = + IssuerGenerationAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + JsonNode baselineVector = vectors.path("validEvents").get(0); + IssuerGenerationAuthorityEvent baseline = + IssuerGenerationAuthorityEventV1Codec.verify(baselineVector.path("event").toString()); + assertThat(baseline.schemaVersion()).isEqualTo("account-auth-issuer-generation-event/v1"); + assertThat(baseline.eventType()).isEqualTo("ISSUER_GENERATION_ADVANCED"); + assertThat(baseline.eventId()).isEqualTo("event-issuer-generation-001"); + assertThat(baseline.requestId()).isEqualTo("request-issuer-generation-001"); + assertThat(baseline.issuerId()).isEqualTo("https://Auth.FireMUD.example/issuer"); + assertThat(baseline.sourceScope()).isEqualTo("issuer/https://Auth.FireMUD.example/issuer"); + assertThat(baseline.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer"); + assertThat(baseline.outboxSequence()).isEqualTo("7"); + assertThat(baseline.issuerAuthGeneration()).isEqualTo("5"); + assertThat(baseline.sourceVersion()).isEqualTo("6"); + + IssuerGenerationAuthorityEvent large = + IssuerGenerationAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.issuerAuthGeneration()).isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changingEveryDeclaredPreimageFieldCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + if (mutation.path("sealValid").asBoolean()) { + IssuerGenerationAuthorityEvent sealed = + IssuerGenerationAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy( + () -> IssuerGenerationAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } else { + assertThatThrownBy(() -> IssuerGenerationAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> IssuerGenerationAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedCanonicalEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + IssuerGenerationAuthorityEvent verified = + IssuerGenerationAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> IssuerGenerationAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAreRejectedBeforeShapeValidation() { + assertThatThrownBy( + () -> + IssuerGenerationAuthorityEventV1Codec.verify( + "{\"eventId\":\"first\",\"eventId\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceIsImmutableAndCanonicalBytesAreCallerOwned() { + JsonNode vector = vectors.path("validEvents").get(0); + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index e1081cd5fa..33d854f663 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -42,6 +42,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; import net.firedevops.firemud.gamesession.service.GameSessionRetainedTenantAssociationService; import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; +import net.firedevops.firemud.gamesession.test.GameInstanceTestFixtures; import net.firedevops.firemud.gamesession.testsupport.RetainedDemoTenantAssociationFixture; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -51,6 +52,7 @@ import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -154,6 +156,49 @@ void syntheticDemoFixtureDoesNotInventUnknownOrContradictoryTenantMappings() { assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); } + @Test + void syntheticDefaultPointerTargetsRemainValidAcrossRepeatedFixtureBaselines() { + Fixture fixture = fixture(); + fixture.seedDefaultDemoAndSandboxPointers(); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + fixture.jdbc, 1L, 1L, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, 501L); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + fixture.jdbc, 2L, 1L, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, 501L); + assertThat(fixture.pointerTargets()) + .containsExactly(new PointerTarget(1L, 1L), new PointerTarget(2L, 2L)); + + RetainedDemoTenantAssociationFixture demoFixture = fixture.demoTenantAssociationFixture(); + AssociationReceipt original = demoFixture.ensureAssociation(1L).orElseThrow(); + String associationXmin = fixture.associationXmin(original.associationRequestId()); + String firstInstanceXmin = fixture.instanceXmin(1L); + assertThatThrownBy( + () -> + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + fixture.jdbc, 1L, 1L, "528846b9-08e8-4c4f-9e3a-e6997a523730", 501L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("contradictory tenant or owner identity"); + assertThat(fixture.instanceXmin(1L)).isEqualTo(firstInstanceXmin); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "synthetic-default-runtime-mutated", + 1L); + assertThat(fixture.capture(1L).evidenceDigest()) + .isNotEqualTo(original.snapshot().evidenceDigest()); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + fixture.jdbc, 1L, 1L, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, 501L); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + fixture.jdbc, 2L, 1L, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, 501L); + + assertThat(fixture.pointerTargets()) + .containsExactly(new PointerTarget(1L, 1L), new PointerTarget(2L, 2L)); + assertThat(fixture.instanceXmin(1L)).isNotEqualTo(firstInstanceXmin); + assertThat(fixture.demoTenantAssociationFixture().ensureAssociation(1L)).contains(original); + assertThat(demoFixture.ensureAssociation(1L)).contains(original); + assertThat(fixture.associationXmin(original.associationRequestId())).isEqualTo(associationXmin); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + @Test void exactRetryReturnsHistoricalReceiptWithoutRecapturingChangedSource() { Fixture fixture = fixture(); @@ -775,7 +820,8 @@ void sourceWriterWaitsUntilAssociationCommitReleasesRetainedRowFence() throws Ex new GameSessionRetainedTenantAssociationRepository( fixture.dsl, delayedSnapshots, NAMESPACE); Fixture delayedFixture = - new Fixture(fixture.dsl, delayedSnapshots, delayedRepository, fixture.transactions); + new Fixture( + fixture.dsl, fixture.jdbc, delayedSnapshots, delayedRepository, fixture.transactions); ExecutorService executor = Executors.newFixedThreadPool(2); try { Future association = @@ -853,11 +899,12 @@ private Fixture fixture() { TransactionTemplate transactions = new TransactionTemplate(transactionManager); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + JdbcTemplate jdbc = new JdbcTemplate(new TransactionAwareDataSourceProxy(dataSource)); GameSessionRetainedTenantSnapshotRepository snapshotRepository = new GameSessionRetainedTenantSnapshotRepository(dsl); GameSessionRetainedTenantAssociationRepository repository = new GameSessionRetainedTenantAssociationRepository(dsl, snapshotRepository, NAMESPACE); - return new Fixture(dsl, snapshotRepository, repository, transactions); + return new Fixture(dsl, jdbc, snapshotRepository, repository, transactions); } private static void assertCheckViolation( @@ -918,8 +965,11 @@ private static String independentlyComputedRequestDigest( } } + private record PointerTarget(long pointerId, long instanceId) {} + private record Fixture( DSLContext dsl, + JdbcTemplate jdbc, GameSessionRetainedTenantSnapshotRepository snapshotRepository, GameSessionRetainedTenantAssociationRepository repository, TransactionTemplate transactions) { @@ -949,6 +999,79 @@ void seedInstance(long tenantId, long instanceId, String runtimeVersion) { 0L); } + void seedDefaultDemoAndSandboxPointers() { + UUID sharedNamespace = UUID.fromString("74430559-8ca5-4f4b-8b71-e116232dcb50"); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + 1L, + sharedNamespace); + seedDefaultPointer( + 1L, + 1L, + "demo", + "production", + "Demo", + "Production", + "a6eea203-4080-4db9-95e3-9ec838aff44a", + sharedNamespace); + seedDefaultPointer( + 2L, + 2L, + "sandbox", + "production", + "Sandbox", + "Production", + "bb8a798d-6706-472a-986b-7eb998748ec2", + sharedNamespace); + } + + private void seedDefaultPointer( + long pointerId, + long instanceId, + String worldSlug, + String realmSlug, + String worldName, + String realmName, + String realmId, + UUID sharedNamespace) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer (" + + "id, world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + pointerId, + worldSlug, + worldName, + realmSlug, + realmName, + 1L, + instanceId, + 1L, + true, + false, + "SHARED", + "OPEN", + "test/default-pointer-bootstrap", + "synthetic retained-snapshot fixture", + true, + UUID.fromString(realmId), + sharedNamespace); + } + + java.util.List pointerTargets() { + return dsl.fetch( + "SELECT id, game_instance_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ? ORDER BY id", + 1L) + .map( + row -> + new PointerTarget( + row.get("id", Long.class), row.get("game_instance_id", Long.class))); + } + GameSessionRetainedTenantSnapshot capture(long legacyTenantId) { return Objects.requireNonNull( transactions.execute( diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java index cf84ab0ade..bc66011175 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java @@ -51,4 +51,109 @@ INSERT INTO game_instances ( "ACTIVE")) .orElseThrow(() -> new IllegalStateException("Game instance insert did not return an id")); } + + /** + * Reuses one explicitly declared synthetic instance row without replacing its tenant or owner. + * This is only for test fixtures that model retained pointers with stable instance identifiers. + */ + public static long ensureDeclaredRunningGameInstance( + JdbcTemplate jdbc, + long instanceId, + long tenantId, + String ownerAccountUuid, + long gameTemplateId) { + if (instanceId <= 0) { + throw new IllegalArgumentException("Declared fixture game instance id must be positive"); + } + UUID declaredOwner = UUID.fromString(ownerAccountUuid); + var existing = + jdbc.query( + "SELECT tenant_id, owner_account_uuid FROM game_instances WHERE id = ?", + (row, index) -> + new ExistingIdentity( + row.getLong("tenant_id"), row.getObject("owner_account_uuid", UUID.class)), + instanceId); + if (existing.isEmpty()) { + jdbc.update( + """ + INSERT INTO game_instances ( + id, + tenant_id, + runtime_version, + script_patch_version, + script_pin_epoch, + script_patch_pinned_control_plane_request_id, + game_template_id, + launch_descriptor_id, + version_id, + release_bundle_id, + version_state_epoch, + generation_config_revision, + remap_set_id, + owner_account_uuid, + status + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + instanceId, + tenantId, + "0.1.0", + "initial", + INITIAL_SCRIPT_PIN_EPOCH, + INITIAL_SCRIPT_PIN_REQUEST_ID, + gameTemplateId, + "stub-launch-descriptor", + gameTemplateId, + PUBLISHED_RELEASE_BUNDLE_ID, + 700L, + "genrev:test:" + gameTemplateId, + null, + declaredOwner, + "ACTIVE"); + } else { + ExistingIdentity identity = existing.get(0); + if (identity.tenantId() != tenantId || !declaredOwner.equals(identity.ownerAccountUuid())) { + throw new IllegalStateException( + "Declared fixture game instance id " + + instanceId + + " has contradictory tenant or owner identity"); + } + jdbc.update( + """ + UPDATE game_instances SET + runtime_version = ?, + script_patch_version = ?, + script_pin_epoch = ?, + script_patch_pinned_control_plane_request_id = ?, + game_template_id = ?, + launch_descriptor_id = ?, + version_id = ?, + release_bundle_id = ?, + version_state_epoch = ?, + generation_config_revision = ?, + remap_set_id = ?, + status = ? + WHERE id = ? + """, + "0.1.0", + "initial", + INITIAL_SCRIPT_PIN_EPOCH, + INITIAL_SCRIPT_PIN_REQUEST_ID, + gameTemplateId, + "stub-launch-descriptor", + gameTemplateId, + PUBLISHED_RELEASE_BUNDLE_ID, + 700L, + "genrev:test:" + gameTemplateId, + null, + "ACTIVE", + instanceId); + } + jdbc.execute( + "SELECT setval('game_instances_id_seq', " + + "GREATEST((SELECT COALESCE(MAX(id), 1) FROM game_instances), " + + "(SELECT last_value FROM game_instances_id_seq)), true)"); + return instanceId; + } + + private record ExistingIdentity(long tenantId, UUID ownerAccountUuid) {} } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index d0d40ba4f2..d1b5db25d5 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -197,13 +197,23 @@ public long freshGameplayBaseline( JdbcTemplate jdbc = jdbc(); clearSyntheticAdmissionPointerState(jdbc); jdbc.execute("TRUNCATE TABLE runtime_region_status RESTART IDENTITY"); - jdbc.execute("TRUNCATE TABLE game_instances RESTART IDENTITY"); if (characterIds.length > 0) { clearScreenBuffers(tenantId, gameplayInstanceId, characterIds); } - long gameInstanceId = - GameInstanceTestFixtures.insertRunningGameInstance( - jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); + long gameInstanceId; + if (tenantId == RetainedDemoTenantAssociationFixture.DEMO_LEGACY_TENANT_ID) { + // These fixed IDs are synthetic test-owner declarations that keep the bootstrapped demo + // and sandbox pointers attached to real source rows before retained snapshot capture. + gameInstanceId = + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + jdbc, 1L, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + jdbc, 2L, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); + } else { + gameInstanceId = + GameInstanceTestFixtures.insertRunningGameInstance( + jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); + } seedRuntimeOwnership(tenantId, gameInstanceId); if (retainedDemoTenantAssociationFixture != null) { retainedDemoTenantAssociationFixture.ensureAssociation(tenantId); @@ -321,7 +331,7 @@ public long insertRunningGameInstance( if (clearExisting) { clearRedis(); jdbc.update("DELETE FROM runtime_region_status"); - jdbc.update("DELETE FROM game_instances"); + // Retained instance identity may still be referenced by canonical admission pointers. } long gameInstanceId = GameInstanceTestFixtures.insertRunningGameInstance( From 58695d165a03f6004236a8a5e27b1a99f1b0eae4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:16:23 +1300 Subject: [PATCH 11/22] Prove issuer source readback over workload mTLS and correct Account UUID attestations --- .github/workflows/ci.yml | 29 + .../account-service/api-contracts.md | 6 + .../game-session-service/api-contracts.md | 2 + .../system-architecture-authentication.md | 2 + design/grpc-docs/grpc-api.md | 11144 ++++++++++++++-- .../player-access-and-session.md | 12 + .../account/v1/issuer_authority_service.proto | 40 + .../AccountIssuerAuthorityEventProducer.java | 124 +- .../AccountIssuerAuthorityGrpcService.java | 321 + ...horityProducerPostgresIntegrationTest.java | 156 + ...countIssuerAuthorityEventProducerTest.java | 59 + ...AccountIssuerAuthorityGrpcServiceTest.java | 374 + .../GameplaySessionAttestationService.java | 43 +- ...GameplaySessionAttestationServiceTest.java | 174 +- .../certs/issuer-authority/README.md | 7 + .../certs/issuer-authority/account.crt | 22 + .../certs/issuer-authority/account.key | 28 + .../resources/certs/issuer-authority/ca.crt | 20 + .../certs/issuer-authority/game-session.crt | 22 + .../certs/issuer-authority/game-session.key | 28 + .../wrong-account-namespace.crt | 22 + .../wrong-account-namespace.key | 28 + .../issuer-authority/wrong-namespace.crt | 22 + .../issuer-authority/wrong-namespace.key | 28 + .../certs/issuer-authority/wrong-service.crt | 22 + .../certs/issuer-authority/wrong-service.key | 28 + .../game-session-service/build.gradle.kts | 1 + .../client/AccountIssuerAuthorityClient.java | 434 + ...suerAuthorityGrpcMtlsCrossServiceTest.java | 263 + .../AccountIssuerAuthorityClientTest.java | 630 + 30 files changed, 12674 insertions(+), 1417 deletions(-) create mode 100644 protos/account/v1/issuer_authority_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/README.md create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.crt create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.key create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/ca.crt create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.crt create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.key create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.crt create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.key create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.crt create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.key create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.crt create mode 100644 services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.key create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java create mode 100644 services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 17cea92f9f..2b0f68810c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1006,6 +1006,32 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Account issuer readback socket mTLS component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:crossServiceTest \ + --tests crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#exactWorkloadIdentitiesCarryCurrentAndHistoricalReadbacksOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#missingClientCertificateFailsTheRequiredTlsHandshakeBeforeProducerAccess()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#[1] clientIdentity = "wrong-service"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#[2] clientIdentity = "wrong-namespace"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#[1] serverIdentity = "game-session"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#[2] serverIdentity = "wrong-account-namespace"' \ + game-session-service + + - name: Upload Account issuer readback socket mTLS proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-issuer-readback-mtls-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/crossServiceTest/TEST-*AccountIssuerAuthorityGrpcMtlsCrossServiceTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session management owner UUID PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | @@ -1090,6 +1116,9 @@ jobs: --require-suite integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#atomicallyAdvancesSourceAndEventAndReadsBackExactCheckpoint()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#exactRetryRecoversLostResponseAndOriginalEventAfterLaterAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#exactHistoricalReadReturnsTheRequestedEventAndCurrentSourceCheckpoint()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#historicalReadDenialsDoNotMutateAndMissingRetainedEventFailsClosed()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#concurrentHistoricalReadWaitsForIssuerRowFenceAndReturnsCommittedCurrentState()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#concurrentExactRequestSerializesAndCommitsOneSourceEvent()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#changedExpectedStateForSameRequestConflictsWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#wrongIssuerStaleRequestAndMissingSourceFailWithoutEnrollmentOrMutation()' \ diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5e0f18ef4e..77bb8706c0 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -155,6 +155,12 @@ Exact retry first reads the immutable event for that request while holding the i Current source readback holds the same issuer fence and returns its positive generation/source version together with exact stream evidence from one Account snapshot. Sequence zero requires the original proved positive baseline and absence of all committed events and contradictory stream state, not merely an absent event/head row; event ID, digest and payload are omitted at zero. A positive checkpoint must exactly match the latest closed issuer event and current counters. Both mutation and readback remain owner-local, unwired components until the authenticated exact-method producer/consumer handoff, delivery and atomic Game Session projection proof pass. They must not be treated as an enabled revocation endpoint or an admission/rebind credential. +Exact historical-event lookup takes the configured issuer and one positive outbox sequence, and holds that same issuer-source fence while reading both the requested immutable event and complete current source/checkpoint. The requested event must match its exact stream/sequence, stored request and event identity, canonical payload and digest; its generation, source version and sequence cannot be ahead of current authority. Missing or contradictory historical evidence denies, including evidence outside the retained window; a high-water mark or equal generation alone never proves a duplicate. The result keeps historical event evidence distinct from current source progress. It cannot authorize admission, replace current recipient evidence, enroll missing authority or fabricate a missing event. The authenticated transport must preserve this complete binding before a consumer can use it for issuer-projection duplicate verification. + +The dedicated internal `account.v1.IssuerAuthorityService/ReadIssuerAuthorityForRuntime` handoff is read-only and distinct from recipient membership RPCs. Account admits only the exact certificate-derived Game Session workload URI in its configured namespace; the Game Session client separately verifies the exact Account server workload URI. A JWT service-name claim, caller-supplied peer or plaintext/in-process transport does not satisfy that authentication. The request has exactly `issuer_id`, canonical non-nil UUID `request_id`, and optional canonical positive decimal `requested_outbox_sequence`; absence selects current readback, while a supplied sequence selects exact historical evidence with current source progress from one fence. Request identity correlates the authenticated read, not a source mutation or an immutable cached current snapshot: a later read may observe advanced current authority. The immutable historical source event remains unchanged. + +The closed response uses `schema_version=account-auth-issuer-source-readback/v1`, exact `target_namespace` and `request_id`, the complete `source_snapshot`, and `requested_event_canonical_json` present only for the explicit historical selector. The snapshot carries exactly the issuer, derived scope and stream, generation/source version and checkpoint sequence as canonical decimal strings, plus the complete canonical latest event only at positive sequence. Historical selection additionally returns the exact requested event's canonical JSON. The receiver rejects unknown fields, mismatched scope/request/namespace, incorrect presence, changed event bytes/digest, regressed or ahead-of-snapshot evidence, and malformed counters; consumer comparison is arbitrary precision. Denials return a terminal gRPC status without partial source content. This transport cannot advance authority, enroll a source, return a recipient tuple/fence, install a projection or admit gameplay. Its candidate handler and client remain unwired until producer, mutual peer authentication, same-snapshot readback and negative proof pass. + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 2ded0f3bdd..b92f9995c5 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -10,6 +10,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: +The dedicated `AccountIssuerAuthorityClient` is an unwired source-only consumer candidate for [Account's issuer readback](../account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). It requires file-backed mutual TLS and the exact Account server workload identity, validates current and explicitly selected historical evidence with the shared issuer-event codec, and compares canonical decimal counters without narrowing them. Its transport result is not a recipient membership snapshot, admission or rebind authorization, an installed issuer projection, or a delivered revocation. Runtime activation remains denied until the complete producer, mutual peer authentication, projection and negative proof passes; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records executed and unavailable proof. + - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; - the shipped owner/status read is `GetRuntimeOwnershipStatus`, not yet the fuller target-state `GetRegionTickStatus` surface described below; - canonical region pause/status remains incomplete for maintenance, reset, migration, and future scoped recovery. Any target region- or tenant-scoped reset must select exactly one explicit gameplay-session policy, `--preserve-sessions` or `--invalidate-sessions`; no preserve default is permitted. Cluster-scoped reset is invalidate-only, and pre-auth transport context is always invalidated or rebuilt. Routine online PostgreSQL backup does not depend on this control; player-facing restore remains blocked instead on the environment-wide cold-start quarantine, convergence, hardening, and proof gaps. See [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model) for the canonical reset policy. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 641d96a824..d6b44e3fc5 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -811,6 +811,8 @@ Because gameplay services do not validate end-user JWTs, they consume the worklo **Implementation status:** The typed `PlayerExecutionContext` shape below is target-only; current wire consumers remain on flat fields plus legacy `session_attestation` carriage. Convergence and consumer proof belong to [ADR 0024](./decisions/adr-0024-trusted-gameplay-workload-delegation.md) and the adopting service contracts, including the current [Game Logic API](./microservices/game-logic-service/api-contracts.md) and [Entity Management API](./microservices/entity-management-service/api-contracts.md); this note does not copy those schemas. +The current legacy gameplay attestation carries the canonical non-nil Account UUID unchanged and compares it exactly; it must not parse that identity as a numeric runtime selector. Its retained runtime tenant key, session, character, instance and pointer dimensions remain their existing numeric identities, distinct from Account's canonical tenant UUID authority boundary. This current-path correction does not implement the typed workload handoff or authorize a numeric-to-UUID association by inference. Internal probes retain their separate non-player identity semantics. + When one trusted gameplay workload calls another on behalf of a player, the request carries a typed protobuf `PlayerExecutionContext` with the required subset of: - `accountId` diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 635a614410..6cab0bb36a 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -31,29 +31,67 @@ for conventions on schema evolution and error handling. See each service's - [DeleteAccountResponse](#account-v1-DeleteAccountResponse) - [ExportAccountRequest](#account-v1-ExportAccountRequest) - [ExportAccountResponse](#account-v1-ExportAccountResponse) + - [ExportTenantDataRequest](#account-v1-ExportTenantDataRequest) + - [ExportTenantDataResponse](#account-v1-ExportTenantDataResponse) - [GetProfileRequest](#account-v1-GetProfileRequest) - [GetProfileResponse](#account-v1-GetProfileResponse) + - [GetRealmAccessGrantForRuntimeRequest](#account-v1-GetRealmAccessGrantForRuntimeRequest) + - [GetRealmAccessGrantForRuntimeResponse](#account-v1-GetRealmAccessGrantForRuntimeResponse) + - [GetTenantEntitlementsForRuntimeRequest](#account-v1-GetTenantEntitlementsForRuntimeRequest) + - [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) + - [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) + - [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) + - [GetTenantMembershipForRuntimeResponse.MembershipVersionEntry](#account-v1-GetTenantMembershipForRuntimeResponse-MembershipVersionEntry) + - [IssueDirectTextConnectScopeRequest](#account-v1-IssueDirectTextConnectScopeRequest) + - [IssueDirectTextConnectScopeResponse](#account-v1-IssueDirectTextConnectScopeResponse) + - [JoinPublicProductionMembershipRequest](#account-v1-JoinPublicProductionMembershipRequest) + - [JoinPublicProductionMembershipResponse](#account-v1-JoinPublicProductionMembershipResponse) - [LinkExternalAccountRequest](#account-v1-LinkExternalAccountRequest) - [LinkExternalAccountResponse](#account-v1-LinkExternalAccountResponse) + - [ListPresenceVisibilityPoliciesRequest](#account-v1-ListPresenceVisibilityPoliciesRequest) + - [ListPresenceVisibilityPoliciesResponse](#account-v1-ListPresenceVisibilityPoliciesResponse) - [PingRequest](#account-v1-PingRequest) - [PingResponse](#account-v1-PingResponse) + - [PresenceVisibilityPolicyEntry](#account-v1-PresenceVisibilityPolicyEntry) + - [RequestEmailLoginOtpRequest](#account-v1-RequestEmailLoginOtpRequest) + - [RequestEmailLoginOtpResponse](#account-v1-RequestEmailLoginOtpResponse) - [RequestEmailVerificationRequest](#account-v1-RequestEmailVerificationRequest) - [RequestEmailVerificationResponse](#account-v1-RequestEmailVerificationResponse) - [RequestPasswordResetRequest](#account-v1-RequestPasswordResetRequest) - [RequestPasswordResetResponse](#account-v1-RequestPasswordResetResponse) + - [RuntimeAccountSecurityCutoff](#account-v1-RuntimeAccountSecurityCutoff) + - [RuntimeAuthorityTuple](#account-v1-RuntimeAuthorityTuple) + - [RuntimeAuthorityTuple.MembershipAuthorityGenerationEntry](#account-v1-RuntimeAuthorityTuple-MembershipAuthorityGenerationEntry) + - [RuntimeAuthorityTuple.TenantAuthorityGenerationEntry](#account-v1-RuntimeAuthorityTuple-TenantAuthorityGenerationEntry) + - [RuntimeMembershipBaseline](#account-v1-RuntimeMembershipBaseline) + - [RuntimeMembershipBaseline.MembershipVersionEntry](#account-v1-RuntimeMembershipBaseline-MembershipVersionEntry) + - [RuntimeOutboxCheckpoint](#account-v1-RuntimeOutboxCheckpoint) + - [RuntimeOutboxSourceEvidence](#account-v1-RuntimeOutboxSourceEvidence) + - [RuntimePrivateRealmGrantVersion](#account-v1-RuntimePrivateRealmGrantVersion) + - [RuntimeTenantBillingCutoff](#account-v1-RuntimeTenantBillingCutoff) + - [RuntimeTenantBillingCutoffEntry](#account-v1-RuntimeTenantBillingCutoffEntry) + - [RuntimeTenantBillingCutoffMap](#account-v1-RuntimeTenantBillingCutoffMap) - [UpdateProfileRequest](#account-v1-UpdateProfileRequest) - [UpdateProfileResponse](#account-v1-UpdateProfileResponse) + - [VerifyEmailLoginOtpRequest](#account-v1-VerifyEmailLoginOtpRequest) - [VerifyEmailRequest](#account-v1-VerifyEmailRequest) - [VerifyEmailResponse](#account-v1-VerifyEmailResponse) - + - [AccountService](#account-v1-AccountService) - + +- [account/v1/issuer_authority_service.proto](#account_v1_issuer_authority_service-proto) + - [IssuerAuthoritySourceSnapshot](#account-v1-IssuerAuthoritySourceSnapshot) + - [ReadIssuerAuthorityForRuntimeRequest](#account-v1-ReadIssuerAuthorityForRuntimeRequest) + - [ReadIssuerAuthorityForRuntimeResponse](#account-v1-ReadIssuerAuthorityForRuntimeResponse) + + - [IssuerAuthorityService](#account-v1-IssuerAuthorityService) + - [account/v1/notification_service.proto](#account_v1_notification_service-proto) - [SendNotificationRequest](#account-v1-SendNotificationRequest) - [SendNotificationResponse](#account-v1-SendNotificationResponse) - + - [NotificationService](#account-v1-NotificationService) - + - [account/v1/payment_service.proto](#account_v1_payment_service-proto) - [CreateDonationRequest](#account-v1-CreateDonationRequest) - [CreateDonationResponse](#account-v1-CreateDonationResponse) @@ -63,9 +101,9 @@ for conventions on schema evolution and error handling. See each service's - [CreateSubscriptionResponse](#account-v1-CreateSubscriptionResponse) - [RefundPaymentRequest](#account-v1-RefundPaymentRequest) - [RefundPaymentResponse](#account-v1-RefundPaymentResponse) - + - [PaymentService](#account-v1-PaymentService) - + - [account/v1/virtual_currency_service.proto](#account_v1_virtual_currency_service-proto) - [AddCurrencyRequest](#account-v1-AddCurrencyRequest) - [AddCurrencyResponse](#account-v1-AddCurrencyResponse) @@ -73,129 +111,394 @@ for conventions on schema evolution and error handling. See each service's - [GetBalanceResponse](#account-v1-GetBalanceResponse) - [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) - [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) - + - [VirtualCurrencyService](#account-v1-VirtualCurrencyService) - + - [automation-scripting/v1/automation_scripting_service.proto](#automation-scripting_v1_automation_scripting_service-proto) - [AddFormationMemberRequest](#automation_scripting-v1-AddFormationMemberRequest) - [AddFormationMemberResponse](#automation_scripting-v1-AddFormationMemberResponse) - [CancelPendingWorkItemsForPatchRequest](#automation_scripting-v1-CancelPendingWorkItemsForPatchRequest) - [CancelPendingWorkItemsForPatchResponse](#automation_scripting-v1-CancelPendingWorkItemsForPatchResponse) + - [CancelPendingWorkItemsForPluginVersionRequest](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionRequest) + - [CancelPendingWorkItemsForPluginVersionResponse](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionResponse) - [CreateFormationRequest](#automation_scripting-v1-CreateFormationRequest) - [CreateFormationResponse](#automation_scripting-v1-CreateFormationResponse) - [DisablePluginRequest](#automation_scripting-v1-DisablePluginRequest) - [DisablePluginResponse](#automation_scripting-v1-DisablePluginResponse) - [DrainPluginRequest](#automation_scripting-v1-DrainPluginRequest) - [DrainPluginResponse](#automation_scripting-v1-DrainPluginResponse) + - [GetAutomationDrainStatusRequest](#automation_scripting-v1-GetAutomationDrainStatusRequest) + - [GetAutomationDrainStatusResponse](#automation_scripting-v1-GetAutomationDrainStatusResponse) + - [GetAutomationPinConvergenceRequest](#automation_scripting-v1-GetAutomationPinConvergenceRequest) + - [GetAutomationPinConvergenceResponse](#automation_scripting-v1-GetAutomationPinConvergenceResponse) + - [GetDraftDesignDigestRequest](#automation_scripting-v1-GetDraftDesignDigestRequest) + - [GetDraftDesignDigestResponse](#automation_scripting-v1-GetDraftDesignDigestResponse) + - [GetPluginPolicyConvergenceRequest](#automation_scripting-v1-GetPluginPolicyConvergenceRequest) + - [GetPluginPolicyConvergenceResponse](#automation_scripting-v1-GetPluginPolicyConvergenceResponse) - [GetPluginStatusRequest](#automation_scripting-v1-GetPluginStatusRequest) - [GetPluginStatusResponse](#automation_scripting-v1-GetPluginStatusResponse) + - [GetScriptEventDefinitionRequest](#automation_scripting-v1-GetScriptEventDefinitionRequest) + - [GetScriptEventDefinitionResponse](#automation_scripting-v1-GetScriptEventDefinitionResponse) + - [GetScriptPatchInstanceRolloutStatusRequest](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusRequest) + - [GetScriptPatchInstanceRolloutStatusResponse](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusResponse) - [GetScriptPatchStatusRequest](#automation_scripting-v1-GetScriptPatchStatusRequest) - [GetScriptPatchStatusResponse](#automation_scripting-v1-GetScriptPatchStatusResponse) - [GetScriptStatusRequest](#automation_scripting-v1-GetScriptStatusRequest) - [GetScriptStatusResponse](#automation_scripting-v1-GetScriptStatusResponse) - [ListFormationMembersRequest](#automation_scripting-v1-ListFormationMembersRequest) - [ListFormationMembersResponse](#automation_scripting-v1-ListFormationMembersResponse) + - [ListPluginRuntimeEventsRequest](#automation_scripting-v1-ListPluginRuntimeEventsRequest) + - [ListPluginRuntimeEventsResponse](#automation_scripting-v1-ListPluginRuntimeEventsResponse) + - [ListScriptDeadLettersRequest](#automation_scripting-v1-ListScriptDeadLettersRequest) + - [ListScriptDeadLettersResponse](#automation_scripting-v1-ListScriptDeadLettersResponse) + - [ListScriptEventDefinitionsRequest](#automation_scripting-v1-ListScriptEventDefinitionsRequest) + - [ListScriptEventDefinitionsResponse](#automation_scripting-v1-ListScriptEventDefinitionsResponse) + - [ListScriptHandoffEventsRequest](#automation_scripting-v1-ListScriptHandoffEventsRequest) + - [ListScriptHandoffEventsResponse](#automation_scripting-v1-ListScriptHandoffEventsResponse) + - [ListScriptPatchInstanceRolloutEventsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsRequest) + - [ListScriptPatchInstanceRolloutEventsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsResponse) + - [ListScriptPatchInstanceRolloutsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutsRequest) + - [ListScriptPatchInstanceRolloutsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutsResponse) - [ListScriptPatchStatusesRequest](#automation_scripting-v1-ListScriptPatchStatusesRequest) - [ListScriptPatchStatusesResponse](#automation_scripting-v1-ListScriptPatchStatusesResponse) + - [ListScriptScheduleInstancesRequest](#automation_scripting-v1-ListScriptScheduleInstancesRequest) + - [ListScriptScheduleInstancesResponse](#automation_scripting-v1-ListScriptScheduleInstancesResponse) + - [ListScriptTimerAuditEventsRequest](#automation_scripting-v1-ListScriptTimerAuditEventsRequest) + - [ListScriptTimerAuditEventsResponse](#automation_scripting-v1-ListScriptTimerAuditEventsResponse) - [NotifyScriptVersionUpdateRequest](#automation_scripting-v1-NotifyScriptVersionUpdateRequest) - [NotifyScriptVersionUpdateResponse](#automation_scripting-v1-NotifyScriptVersionUpdateResponse) + - [ObserveRuntimeTickProgressRequest](#automation_scripting-v1-ObserveRuntimeTickProgressRequest) + - [ObserveRuntimeTickProgressResponse](#automation_scripting-v1-ObserveRuntimeTickProgressResponse) - [PingRequest](#automation_scripting-v1-PingRequest) - [PingResponse](#automation_scripting-v1-PingResponse) + - [PluginPolicyViolation](#automation_scripting-v1-PluginPolicyViolation) + - [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) + - [PluginRuntimeEventEntry](#automation_scripting-v1-PluginRuntimeEventEntry) + - [ReplayDeadLetteredWorkItemResult](#automation_scripting-v1-ReplayDeadLetteredWorkItemResult) + - [ReplayDeadLetteredWorkItemsRequest](#automation_scripting-v1-ReplayDeadLetteredWorkItemsRequest) + - [ReplayDeadLetteredWorkItemsResponse](#automation_scripting-v1-ReplayDeadLetteredWorkItemsResponse) + - [ScriptDeadLetterEntry](#automation_scripting-v1-ScriptDeadLetterEntry) + - [ScriptEventBinding](#automation_scripting-v1-ScriptEventBinding) + - [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) + - [ScriptHandoffEventEntry](#automation_scripting-v1-ScriptHandoffEventEntry) + - [ScriptPatchInstanceRolloutEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEntry) + - [ScriptPatchInstanceRolloutEventEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEventEntry) + - [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) - [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) + - [ScriptScheduleInstanceEntry](#automation_scripting-v1-ScriptScheduleInstanceEntry) + - [ScriptTimerAuditEventEntry](#automation_scripting-v1-ScriptTimerAuditEventEntry) + - [SetAutomationAdmissionModeRequest](#automation_scripting-v1-SetAutomationAdmissionModeRequest) + - [SetAutomationAdmissionModeResponse](#automation_scripting-v1-SetAutomationAdmissionModeResponse) - [SetPluginActiveVersionRequest](#automation_scripting-v1-SetPluginActiveVersionRequest) - [SetPluginActiveVersionResponse](#automation_scripting-v1-SetPluginActiveVersionResponse) - [TriggerScriptEventRequest](#automation_scripting-v1-TriggerScriptEventRequest) - [TriggerScriptEventResponse](#automation_scripting-v1-TriggerScriptEventResponse) - [UpdateScriptRequest](#automation_scripting-v1-UpdateScriptRequest) - [UpdateScriptResponse](#automation_scripting-v1-UpdateScriptResponse) - + + - [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) - [PluginState](#automation_scripting-v1-PluginState) + - [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) - [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) - [TriggerAdmissionOutcome](#automation_scripting-v1-TriggerAdmissionOutcome) - [TriggerMode](#automation_scripting-v1-TriggerMode) - + - [AutomationScriptingControlPlaneService](#automation_scripting-v1-AutomationScriptingControlPlaneService) - [AutomationScriptingService](#automation_scripting-v1-AutomationScriptingService) - + - [entity-management/v1/entity_management_service.proto](#entity-management_v1_entity_management_service-proto) + - [ActorConditionState](#entity_management-v1-ActorConditionState) + - [ActorResourceValue](#entity_management-v1-ActorResourceValue) + - [ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) + - [ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) - [Character](#entity_management-v1-Character) + - [CleanupRuntimeInstanceRequest](#entity_management-v1-CleanupRuntimeInstanceRequest) + - [CleanupRuntimeInstanceResponse](#entity_management-v1-CleanupRuntimeInstanceResponse) + - [ContainerItem](#entity_management-v1-ContainerItem) - [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) - [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) + - [DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) + - [DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) + - [EquipmentItem](#entity_management-v1-EquipmentItem) + - [FindCharacterByNameRequest](#entity_management-v1-FindCharacterByNameRequest) + - [FindCharacterByNameResponse](#entity_management-v1-FindCharacterByNameResponse) - [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) - [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) + - [InventoryItem](#entity_management-v1-InventoryItem) - [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) - [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) + - [ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) + - [ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) + - [ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) + - [ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) - [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) - [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) + - [ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) + - [ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) + - [PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) + - [PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) - [PingRequest](#entity_management-v1-PingRequest) - [PingResponse](#entity_management-v1-PingResponse) + - [PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) + - [PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) + - [QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) + - [QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) - [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) - [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) + - [RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) + - [RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) - [RoomEntity](#entity_management-v1-RoomEntity) + - [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) + - [TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) + - [TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) - [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) - [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) - + - [ValidateEntityTemplateReferenceRequest](#entity_management-v1-ValidateEntityTemplateReferenceRequest) + - [ValidateEntityTemplateReferenceResponse](#entity_management-v1-ValidateEntityTemplateReferenceResponse) + - [ValidateEntityUpgradeMappingsRequest](#entity_management-v1-ValidateEntityUpgradeMappingsRequest) + - [ValidateEntityUpgradeMappingsResponse](#entity_management-v1-ValidateEntityUpgradeMappingsResponse) + - [WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) + - [WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) + + - [EntityTemplateReferenceType](#entity_management-v1-EntityTemplateReferenceType) - [EntityType](#entity_management-v1-EntityType) + - [PlayableStateScope](#entity_management-v1-PlayableStateScope) - [ReloadHint](#entity_management-v1-ReloadHint) - + - [UpgradeValidationResult](#entity_management-v1-UpgradeValidationResult) + - [EntityManagementService](#entity_management-v1-EntityManagementService) - + - [game-design/v1/game_design_service.proto](#game-design_v1_game_design_service-proto) + - [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) + - [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) + - [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) + - [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) + - [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) + - [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) + - [CanDeleteVersionAssetsResponse](#gamedesign-v1-CanDeleteVersionAssetsResponse) + - [CommandCapabilitiesSettingsOverride](#gamedesign-v1-CommandCapabilitiesSettingsOverride) + - [CommandHistorySettingsOverride](#gamedesign-v1-CommandHistorySettingsOverride) + - [CommunicationSettingsOverride](#gamedesign-v1-CommunicationSettingsOverride) + - [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) + - [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) + - [CreateTemplateRemapSetRequest](#gamedesign-v1-CreateTemplateRemapSetRequest) + - [CreateTemplateRemapSetResponse](#gamedesign-v1-CreateTemplateRemapSetResponse) + - [DeleteHelpTopicRequest](#gamedesign-v1-DeleteHelpTopicRequest) + - [DeleteHelpTopicResponse](#gamedesign-v1-DeleteHelpTopicResponse) + - [DeleteSettingsDomainOverrideRequest](#gamedesign-v1-DeleteSettingsDomainOverrideRequest) + - [DeleteSettingsDomainOverrideResponse](#gamedesign-v1-DeleteSettingsDomainOverrideResponse) + - [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) + - [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) + - [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) + - [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) + - [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) + - [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) + - [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) + - [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) + - [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) + - [GetPublishedScriptPatchVersionRequest](#gamedesign-v1-GetPublishedScriptPatchVersionRequest) + - [GetPublishedScriptPatchVersionResponse](#gamedesign-v1-GetPublishedScriptPatchVersionResponse) + - [GetScopedSettingsOverridesRequest](#gamedesign-v1-GetScopedSettingsOverridesRequest) + - [GetScopedSettingsOverridesResponse](#gamedesign-v1-GetScopedSettingsOverridesResponse) + - [GetTemplateRemapSetRequest](#gamedesign-v1-GetTemplateRemapSetRequest) + - [GetTemplateRemapSetResponse](#gamedesign-v1-GetTemplateRemapSetResponse) + - [GetVersionAssetArtifactStateRequest](#gamedesign-v1-GetVersionAssetArtifactStateRequest) + - [GetVersionAssetArtifactStateResponse](#gamedesign-v1-GetVersionAssetArtifactStateResponse) + - [GetVersionAssetPurgeStatusRequest](#gamedesign-v1-GetVersionAssetPurgeStatusRequest) + - [GetVersionAssetPurgeStatusResponse](#gamedesign-v1-GetVersionAssetPurgeStatusResponse) + - [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) + - [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) + - [HelpTopic](#gamedesign-v1-HelpTopic) + - [HelpTopicScope](#gamedesign-v1-HelpTopicScope) + - [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) + - [ListHelpTopicsRequest](#gamedesign-v1-ListHelpTopicsRequest) + - [ListHelpTopicsResponse](#gamedesign-v1-ListHelpTopicsResponse) + - [ListPluginVersionStatusEventsRequest](#gamedesign-v1-ListPluginVersionStatusEventsRequest) + - [ListPluginVersionStatusEventsResponse](#gamedesign-v1-ListPluginVersionStatusEventsResponse) + - [ListPluginVersionStatusesRequest](#gamedesign-v1-ListPluginVersionStatusesRequest) + - [ListPluginVersionStatusesResponse](#gamedesign-v1-ListPluginVersionStatusesResponse) - [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) - [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) + - [MovementSettingsOverride](#gamedesign-v1-MovementSettingsOverride) + - [ParticipantDigest](#gamedesign-v1-ParticipantDigest) - [PingRequest](#gamedesign-v1-PingRequest) - [PingResponse](#gamedesign-v1-PingResponse) + - [PluginVersionStatusEventEntry](#gamedesign-v1-PluginVersionStatusEventEntry) + - [PresentationPromptOverride](#gamedesign-v1-PresentationPromptOverride) + - [PresentationSettingsOverride](#gamedesign-v1-PresentationSettingsOverride) + - [PublishPluginVersionRequest](#gamedesign-v1-PublishPluginVersionRequest) + - [PublishPluginVersionResponse](#gamedesign-v1-PublishPluginVersionResponse) - [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) - [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) - [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) - [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) + - [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) + - [PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) + - [PublishedScriptPatchVersion](#gamedesign-v1-PublishedScriptPatchVersion) + - [PutHelpTopicRequest](#gamedesign-v1-PutHelpTopicRequest) + - [PutHelpTopicResponse](#gamedesign-v1-PutHelpTopicResponse) + - [PutSettingsDomainOverrideRequest](#gamedesign-v1-PutSettingsDomainOverrideRequest) + - [PutSettingsDomainOverrideResponse](#gamedesign-v1-PutSettingsDomainOverrideResponse) + - [ReconnectionBufferOverride](#gamedesign-v1-ReconnectionBufferOverride) + - [ReconnectionPolicyOverride](#gamedesign-v1-ReconnectionPolicyOverride) + - [ReconnectionSettingsOverride](#gamedesign-v1-ReconnectionSettingsOverride) + - [RepairPublishedVersionAssetsRequest](#gamedesign-v1-RepairPublishedVersionAssetsRequest) + - [RepairPublishedVersionAssetsResponse](#gamedesign-v1-RepairPublishedVersionAssetsResponse) + - [ResolveHelpTopicRequest](#gamedesign-v1-ResolveHelpTopicRequest) + - [ResolveHelpTopicResponse](#gamedesign-v1-ResolveHelpTopicResponse) + - [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) + - [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) + - [RevokePluginVersionRequest](#gamedesign-v1-RevokePluginVersionRequest) + - [RevokePluginVersionResponse](#gamedesign-v1-RevokePluginVersionResponse) - [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) - [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) + - [SettingsOverrides](#gamedesign-v1-SettingsOverrides) + - [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) + - [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) + - [TombstoneVersionAssetsRequest](#gamedesign-v1-TombstoneVersionAssetsRequest) + - [TombstoneVersionAssetsResponse](#gamedesign-v1-TombstoneVersionAssetsResponse) + - [UploadPluginBundleRequest](#gamedesign-v1-UploadPluginBundleRequest) + - [UploadPluginBundleResponse](#gamedesign-v1-UploadPluginBundleResponse) - [Version](#gamedesign-v1-Version) - + - [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) + - [VersionAssetDeletionEligibility](#gamedesign-v1-VersionAssetDeletionEligibility) + - [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) + - [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) + - [WorldDesignMutationRevision](#gamedesign-v1-WorldDesignMutationRevision) + - [WorldTopologySettingsOverride](#gamedesign-v1-WorldTopologySettingsOverride) + + - [ArtifactState](#gamedesign-v1-ArtifactState) + - [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) + - [PresentationColorMode](#gamedesign-v1-PresentationColorMode) + - [SettingsDomain](#gamedesign-v1-SettingsDomain) + - [TemplateRemapSetStatus](#gamedesign-v1-TemplateRemapSetStatus) + - [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) + - [WorldTopologyScopeModel](#gamedesign-v1-WorldTopologyScopeModel) + - [GameDesignService](#gamedesign-v1-GameDesignService) - + +- [game-design/v1/tenant_identity_service.proto](#game-design_v1_tenant_identity_service-proto) + - [GameSessionTenantAssociationManifestEvidence](#gamedesign-v1-GameSessionTenantAssociationManifestEvidence) + - [ResolveAuthoredWorldSourceRequest](#gamedesign-v1-ResolveAuthoredWorldSourceRequest) + - [ResolveAuthoredWorldSourceResponse](#gamedesign-v1-ResolveAuthoredWorldSourceResponse) + - [ResolveFreshTenantCreationRequest](#gamedesign-v1-ResolveFreshTenantCreationRequest) + - [ResolveFreshTenantCreationResponse](#gamedesign-v1-ResolveFreshTenantCreationResponse) + - [ResolveLegacyAccountTenantAssociationRequest](#gamedesign-v1-ResolveLegacyAccountTenantAssociationRequest) + - [ResolveLegacyAccountTenantAssociationResponse](#gamedesign-v1-ResolveLegacyAccountTenantAssociationResponse) + - [ResolveLegacyGameSessionTenantAssociationRequest](#gamedesign-v1-ResolveLegacyGameSessionTenantAssociationRequest) + - [ResolveLegacyGameSessionTenantAssociationResponse](#gamedesign-v1-ResolveLegacyGameSessionTenantAssociationResponse) + - [ResolveLegacyGameTenantIdentityRequest](#gamedesign-v1-ResolveLegacyGameTenantIdentityRequest) + - [ResolveLegacyGameTenantIdentityResponse](#gamedesign-v1-ResolveLegacyGameTenantIdentityResponse) + - [ResolveRuntimeTenantIdentityRequest](#gamedesign-v1-ResolveRuntimeTenantIdentityRequest) + - [ResolveRuntimeTenantIdentityResponse](#gamedesign-v1-ResolveRuntimeTenantIdentityResponse) + + - [TenantIdentityService](#gamedesign-v1-TenantIdentityService) + - [game-logic/v1/game_logic_service.proto](#game-logic_v1_game_logic_service-proto) - - [BroadcastSayRequest](#game_logic-v1-BroadcastSayRequest) - - [BroadcastSayResponse](#game_logic-v1-BroadcastSayResponse) + - [CommunicationRecipientView](#game_logic-v1-CommunicationRecipientView) - [DoorAmbientState](#game_logic-v1-DoorAmbientState) + - [DropCarriedItemRequest](#game_logic-v1-DropCarriedItemRequest) - [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) - [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) + - [GetDraftDesignDigestRequest](#game_logic-v1-GetDraftDesignDigestRequest) + - [GetDraftDesignDigestResponse](#game_logic-v1-GetDraftDesignDigestResponse) - [HazardAmbientState](#game_logic-v1-HazardAmbientState) - [LookExit](#game_logic-v1-LookExit) - [LookRequest](#game_logic-v1-LookRequest) - [LookResult](#game_logic-v1-LookResult) + - [MoveRequest](#game_logic-v1-MoveRequest) + - [MoveResult](#game_logic-v1-MoveResult) + - [PickupVisibleRoomItemRequest](#game_logic-v1-PickupVisibleRoomItemRequest) - [PingRequest](#game_logic-v1-PingRequest) - [PingResponse](#game_logic-v1-PingResponse) - [RoomAmbientState](#game_logic-v1-RoomAmbientState) - [RoomEntity](#game_logic-v1-RoomEntity) - - - [ChatAlias](#game_logic-v1-ChatAlias) + - [SendCommunicationRequest](#game_logic-v1-SendCommunicationRequest) + - [SendCommunicationResponse](#game_logic-v1-SendCommunicationResponse) + + - [CommunicationPerception](#game_logic-v1-CommunicationPerception) + - [CommunicationRecipientRole](#game_logic-v1-CommunicationRecipientRole) + - [CommunicationTargetKind](#game_logic-v1-CommunicationTargetKind) + - [CommunicationType](#game_logic-v1-CommunicationType) - [DoorState](#game_logic-v1-DoorState) - [EntityType](#game_logic-v1-EntityType) - [HazardState](#game_logic-v1-HazardState) - + - [GameLogicService](#game_logic-v1-GameLogicService) - + - [game-session/v1/game_session_service.proto](#game-session_v1_game_session_service-proto) + - [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) + - [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) + - [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) + - [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) + - [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) - [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) - [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) + - [ExecutePreparedVersionCutoverRequest](#game_session-v1-ExecutePreparedVersionCutoverRequest) + - [ExecutePreparedVersionCutoverResponse](#game_session-v1-ExecutePreparedVersionCutoverResponse) + - [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) + - [GameInstanceRuntimeState](#game_session-v1-GameInstanceRuntimeState) + - [GameplayAdmissionPointer](#game_session-v1-GameplayAdmissionPointer) + - [GameplayCommandStatus](#game_session-v1-GameplayCommandStatus) + - [GameplayRealm](#game_session-v1-GameplayRealm) + - [GameplayWorld](#game_session-v1-GameplayWorld) + - [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) + - [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) + - [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) + - [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) + - [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) + - [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) + - [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) + - [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) - [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) - [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) + - [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) + - [GetPreparedVersionUpgradeResponse](#game_session-v1-GetPreparedVersionUpgradeResponse) + - [GetRemoteCommandCoordinatorRequest](#game_session-v1-GetRemoteCommandCoordinatorRequest) + - [GetRemoteCommandCoordinatorResponse](#game_session-v1-GetRemoteCommandCoordinatorResponse) + - [GetRemoteFollowupRequest](#game_session-v1-GetRemoteFollowupRequest) + - [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) + - [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) + - [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) + - [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) + - [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) - [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) - [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) + - [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) + - [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) + - [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) + - [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) + - [ListGameplayRealmsRequest](#game_session-v1-ListGameplayRealmsRequest) + - [ListGameplayRealmsResponse](#game_session-v1-ListGameplayRealmsResponse) + - [ListGameplayWorldsRequest](#game_session-v1-ListGameplayWorldsRequest) + - [ListGameplayWorldsResponse](#game_session-v1-ListGameplayWorldsResponse) + - [ListRemoteCommandCoordinatorsRequest](#game_session-v1-ListRemoteCommandCoordinatorsRequest) + - [ListRemoteCommandCoordinatorsResponse](#game_session-v1-ListRemoteCommandCoordinatorsResponse) + - [ListRemoteFollowupResultsRequest](#game_session-v1-ListRemoteFollowupResultsRequest) + - [ListRemoteFollowupResultsResponse](#game_session-v1-ListRemoteFollowupResultsResponse) + - [ListRemoteFollowupsRequest](#game_session-v1-ListRemoteFollowupsRequest) + - [ListRemoteFollowupsResponse](#game_session-v1-ListRemoteFollowupsResponse) - [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) - [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) - [PauseTicksRequest](#game_session-v1-PauseTicksRequest) - [PauseTicksResponse](#game_session-v1-PauseTicksResponse) - [PingRequest](#game_session-v1-PingRequest) - [PingResponse](#game_session-v1-PingResponse) + - [PluginPublicationLink](#game_session-v1-PluginPublicationLink) + - [PrepareVersionUpgradeRequest](#game_session-v1-PrepareVersionUpgradeRequest) + - [PrepareVersionUpgradeResponse](#game_session-v1-PrepareVersionUpgradeResponse) + - [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) - [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) - [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) - [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) - [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) + - [QueryAccountPresenceRequest](#game_session-v1-QueryAccountPresenceRequest) + - [QueryAccountPresenceResponse](#game_session-v1-QueryAccountPresenceResponse) - [QueryStateRequest](#game_session-v1-QueryStateRequest) - [QueryStateResponse](#game_session-v1-QueryStateResponse) + - [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) + - [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) + - [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) - [RestartSessionRequest](#game_session-v1-RestartSessionRequest) - [RestartSessionResponse](#game_session-v1-RestartSessionResponse) - [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) @@ -204,6 +507,12 @@ for conventions on schema evolution and error handling. See each service's - [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) - [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) - [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) + - [RuntimeOwnershipStatus](#game_session-v1-RuntimeOwnershipStatus) + - [ScheduleRemoteFollowupRequest](#game_session-v1-ScheduleRemoteFollowupRequest) + - [ScheduleRemoteFollowupResponse](#game_session-v1-ScheduleRemoteFollowupResponse) + - [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) + - [SetAdmissionPointerRequest](#game_session-v1-SetAdmissionPointerRequest) + - [SetAdmissionPointerResponse](#game_session-v1-SetAdmissionPointerResponse) - [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) - [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) - [StartSessionRequest](#game_session-v1-StartSessionRequest) @@ -212,55 +521,101 @@ for conventions on schema evolution and error handling. See each service's - [StopSessionResponse](#game_session-v1-StopSessionResponse) - [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) - [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) - + - [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) + - [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) + - [ValidateInstanceCutoverCompatibilityRequest](#game_session-v1-ValidateInstanceCutoverCompatibilityRequest) + - [ValidateInstanceCutoverCompatibilityResponse](#game_session-v1-ValidateInstanceCutoverCompatibilityResponse) + + - [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) + - [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) + - [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) + - [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) - [TickStatus](#game_session-v1-TickStatus) - + - [GameSessionControlPlaneService](#game_session-v1-GameSessionControlPlaneService) - [GameSessionService](#game_session-v1-GameSessionService) - + - [logging-admin/v1/logging_admin_service.proto](#logging-admin_v1_logging_admin_service-proto) - [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) - [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) + - [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) + - [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) + - [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) + - [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) - [PingRequest](#logging_admin-v1-PingRequest) - [PingResponse](#logging_admin-v1-PingResponse) - [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) - [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) + - [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) + - [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) - [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) - [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) - + + - [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) + - [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) + - [AccountAuditScope](#logging_admin-v1-AccountAuditScope) + - [LoggingAdminService](#logging_admin-v1-LoggingAdminService) - + - [logging-admin/v1/report_service.proto](#logging-admin_v1_report_service-proto) - [CreateReportRequest](#logging_admin-v1-CreateReportRequest) - [CreateReportResponse](#logging_admin-v1-CreateReportResponse) - + - [ReportService](#logging_admin-v1-ReportService) - + - [shared/v1/errors.proto](#shared_v1_errors-proto) - [ErrorDetail](#shared-v1-ErrorDetail) - + - [shared/v1/instance_refs.proto](#shared_v1_instance_refs-proto) - [RoomInstanceRef](#shared-v1-RoomInstanceRef) - + - [shared/v1/paging.proto](#shared_v1_paging-proto) - [PagingRequest](#shared-v1-PagingRequest) - + +- [shared/v1/player_execution_context.proto](#shared_v1_player_execution_context-proto) + - [PlayerExecutionContext](#shared-v1-PlayerExecutionContext) + - [social-groups/v1/social_groups_service.proto](#social-groups_v1_social_groups_service-proto) - [AddFriendRequest](#social_groups-v1-AddFriendRequest) - [AddFriendResponse](#social_groups-v1-AddFriendResponse) - [CreateGuildRequest](#social_groups-v1-CreateGuildRequest) - [CreateGuildResponse](#social_groups-v1-CreateGuildResponse) + - [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) + - [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) + - [FriendRosterSummary](#social_groups-v1-FriendRosterSummary) + - [GetFriendByOrdinalRequest](#social_groups-v1-GetFriendByOrdinalRequest) + - [GetFriendByOrdinalResponse](#social_groups-v1-GetFriendByOrdinalResponse) + - [GetFriendPresencePolicyRequest](#social_groups-v1-GetFriendPresencePolicyRequest) + - [GetFriendPresencePolicyResponse](#social_groups-v1-GetFriendPresencePolicyResponse) + - [GetFriendRequest](#social_groups-v1-GetFriendRequest) + - [GetFriendResponse](#social_groups-v1-GetFriendResponse) + - [GetFriendRosterSummaryRequest](#social_groups-v1-GetFriendRosterSummaryRequest) + - [GetFriendRosterSummaryResponse](#social_groups-v1-GetFriendRosterSummaryResponse) + - [ListFriendPresenceRequest](#social_groups-v1-ListFriendPresenceRequest) + - [ListFriendPresenceResponse](#social_groups-v1-ListFriendPresenceResponse) + - [ListFriendsRequest](#social_groups-v1-ListFriendsRequest) + - [ListFriendsResponse](#social_groups-v1-ListFriendsResponse) - [PingRequest](#social_groups-v1-PingRequest) - [PingResponse](#social_groups-v1-PingResponse) + - [RemoveFriendByOrdinalRequest](#social_groups-v1-RemoveFriendByOrdinalRequest) + - [RemoveFriendByOrdinalResponse](#social_groups-v1-RemoveFriendByOrdinalResponse) + - [RemoveFriendRequest](#social_groups-v1-RemoveFriendRequest) + - [RemoveFriendResponse](#social_groups-v1-RemoveFriendResponse) - [SendMailRequest](#social_groups-v1-SendMailRequest) - [SendMailResponse](#social_groups-v1-SendMailResponse) - [SendMessageRequest](#social_groups-v1-SendMessageRequest) - [SendMessageResponse](#social_groups-v1-SendMessageResponse) - + - [UpdateFriendPresencePolicyRequest](#social_groups-v1-UpdateFriendPresencePolicyRequest) + - [UpdateFriendPresencePolicyResponse](#social_groups-v1-UpdateFriendPresencePolicyResponse) + - [ChatType](#social_groups-v1-ChatType) - + - [FriendPresenceActivityState](#social_groups-v1-FriendPresenceActivityState) + - [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) + - [FriendRecentPresenceDisposition](#social_groups-v1-FriendRecentPresenceDisposition) + - [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) + - [SocialGroupsService](#social_groups-v1-SocialGroupsService) - + - [spring-cloud-gateway/v1/gateway_management_service.proto](#spring-cloud-gateway_v1_gateway_management_service-proto) - [PingRequest](#gateway-v1-PingRequest) - [PingResponse](#gateway-v1-PingResponse) @@ -268,45 +623,78 @@ for conventions on schema evolution and error handling. See each service's - [RemoveRouteResponse](#gateway-v1-RemoveRouteResponse) - [UpsertRouteRequest](#gateway-v1-UpsertRouteRequest) - [UpsertRouteResponse](#gateway-v1-UpsertRouteResponse) - + - [GatewayManagementService](#gateway-v1-GatewayManagementService) - + - [tcp-proxy/v1/tcp_proxy_service.proto](#tcp-proxy_v1_tcp_proxy_service-proto) - [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) - [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) - [PingRequest](#tcp_proxy-v1-PingRequest) - [PingResponse](#tcp_proxy-v1-PingResponse) - + - [TcpProxyService](#tcp_proxy-v1-TcpProxyService) - + - [world-management/v1/world_management_service.proto](#world-management_v1_world_management_service-proto) + - [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) + - [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) - [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) - [ApplyRoomAmbientStatePatchResponse](#world_management-v1-ApplyRoomAmbientStatePatchResponse) + - [ApplyWorldDesignMutationRequest](#world_management-v1-ApplyWorldDesignMutationRequest) + - [ApplyWorldDesignMutationResponse](#world_management-v1-ApplyWorldDesignMutationResponse) - [DoorAmbientState](#world_management-v1-DoorAmbientState) + - [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) + - [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) + - [GeneratedRoomDesignMutation](#world_management-v1-GeneratedRoomDesignMutation) + - [GeneratedRoomExitDesignMutation](#world_management-v1-GeneratedRoomExitDesignMutation) + - [GeneratedWorldEntitySpawnBindingDesignMutation](#world_management-v1-GeneratedWorldEntitySpawnBindingDesignMutation) + - [GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) - [GetDraftDesignDigestRequest](#world_management-v1-GetDraftDesignDigestRequest) - [GetDraftDesignDigestResponse](#world_management-v1-GetDraftDesignDigestResponse) - [GetRoomRequest](#world_management-v1-GetRoomRequest) - [GetRoomResponse](#world_management-v1-GetRoomResponse) - - [RuntimeRoom](#world_management-v1-RuntimeRoom) - [GetRoomSnapshotRequest](#world_management-v1-GetRoomSnapshotRequest) - [GetRoomSnapshotResponse](#world_management-v1-GetRoomSnapshotResponse) + - [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) + - [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) - [HazardAmbientState](#world_management-v1-HazardAmbientState) - [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) - [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) - [PingRequest](#world_management-v1-PingRequest) - [PingResponse](#world_management-v1-PingResponse) + - [PrepareWorldInstanceRequest](#world_management-v1-PrepareWorldInstanceRequest) + - [PrepareWorldInstanceResponse](#world_management-v1-PrepareWorldInstanceResponse) + - [RegionDesignMutation](#world_management-v1-RegionDesignMutation) - [RoomAmbientState](#world_management-v1-RoomAmbientState) - [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) + - [RoomDesignMutation](#world_management-v1-RoomDesignMutation) + - [RoomExitDesignMutation](#world_management-v1-RoomExitDesignMutation) - [RoomExitSnapshot](#world_management-v1-RoomExitSnapshot) - [RoomOccupant](#world_management-v1-RoomOccupant) - [RoomSnapshot](#world_management-v1-RoomSnapshot) - + - [RuntimeRoom](#world_management-v1-RuntimeRoom) + - [TerminateWorldInstanceRequest](#world_management-v1-TerminateWorldInstanceRequest) + - [TerminateWorldInstanceResponse](#world_management-v1-TerminateWorldInstanceResponse) + - [ValidateWorldUpgradeMappingsRequest](#world_management-v1-ValidateWorldUpgradeMappingsRequest) + - [ValidateWorldUpgradeMappingsResponse](#world_management-v1-ValidateWorldUpgradeMappingsResponse) + - [WorldEntitySpawnBindingDesignMutation](#world_management-v1-WorldEntitySpawnBindingDesignMutation) + - [WorldGenerationSubtreeDesignMutation](#world_management-v1-WorldGenerationSubtreeDesignMutation) + - [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) + - [ZoneDesignMutation](#world_management-v1-ZoneDesignMutation) + - [DoorState](#world_management-v1-DoorState) + - [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) - [HazardState](#world_management-v1-HazardState) - [RoomOccupantType](#world_management-v1-RoomOccupantType) - + - [UpgradeValidationResult](#world_management-v1-UpgradeValidationResult) + - [WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) + - [WorldDesignMutationOperation](#world_management-v1-WorldDesignMutationOperation) + - [WorldDesignMutationResult](#world_management-v1-WorldDesignMutationResult) + - [WorldDesignScopeMutationPolicy](#world_management-v1-WorldDesignScopeMutationPolicy) + - [WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) + - [WorldInstanceLifecycleStatus](#world_management-v1-WorldInstanceLifecycleStatus) + - [WorldManagementService](#world_management-v1-WorldManagementService) - + - [Scalar Value Types](#scalar-value-types) @@ -326,10 +714,8 @@ for conventions on schema evolution and error handling. See each service's | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| username | [string](#string) | | | | password | [string](#string) | | | -| otp | [string](#string) | | | +| email | [string](#string) | | | @@ -345,7 +731,7 @@ for conventions on schema evolution and error handling. See each service's | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | auth_token | [string](#string) | | | -| account_id | [string](#string) | | | +| account_id | [string](#string) | | Canonical non-nil Account UUID from the authenticated persisted source row, never its numeric PK. | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -361,7 +747,6 @@ for conventions on schema evolution and error handling. See each service's | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | token | [string](#string) | | | | new_password | [string](#string) | | | @@ -411,7 +796,7 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| account_id | [string](#string) | | Unique identifier of the newly created account. | +| account_id | [string](#string) | | Canonical non-nil Account UUID of the newly created account. | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | Details about why the creation failed, if applicable. | @@ -427,7 +812,6 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | @@ -459,7 +843,6 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | @@ -476,7 +859,7 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | account_json | [string](#string) | | | -| profile_json | [string](#string) | | | +| profiles_json | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -484,9 +867,9 @@ Result of a CreateAccount call. - + -### GetProfileRequest +### ExportTenantDataRequest @@ -500,14 +883,16 @@ Result of a CreateAccount call. - + -### GetProfileResponse +### ExportTenantDataResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_json | [string](#string) | | | | profile_json | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -516,33 +901,31 @@ Result of a CreateAccount call. - + -### LinkExternalAccountRequest +### GetProfileRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| provider | [string](#string) | | | -| external_id | [string](#string) | | | +| account_id | [string](#string) | | Canonical non-nil Account UUID, exactly matching the authenticated caller subject. | - + -### LinkExternalAccountResponse +### GetProfileResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| profile_json | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -550,201 +933,233 @@ Result of a CreateAccount call. - - -### PingRequest -Empty request used to verify that the service is reachable. - - + +### GetRealmAccessGrantForRuntimeRequest - - -### PingResponse -Basic ping response containing a greeting and optional error details. - - | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | Message describing the current status of the service. | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | Populated on application-level failure conditions. | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| request_id | [string](#string) | | | - + -### RequestEmailVerificationRequest +### GetRealmAccessGrantForRuntimeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| granted | [bool](#bool) | | | +| grant_version | [uint64](#uint64) | | | +| evaluated_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### RequestEmailVerificationResponse +### GetTenantEntitlementsForRuntimeRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| request_id | [string](#string) | | | - + -### RequestPasswordResetRequest +### GetTenantEntitlementsForRuntimeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| email | [string](#string) | | | +| gameplay_available | [bool](#bool) | | | +| entitlement_version | [uint64](#uint64) | | | +| tenant_billing_sequence | [uint64](#uint64) | | | +| evaluated_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| allow_public_join | [bool](#bool) | | | - + -### RequestPasswordResetResponse +### GetTenantMembershipForRuntimeRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| player_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | account_id and tenant_id are exact canonical UUIDs, never private numeric row keys. The complete selected target is checked separately; this unsigned context is not authority. | - + -### UpdateProfileRequest +### GetTenantMembershipForRuntimeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | -| profile_json | [string](#string) | | | +| tenant_id | [string](#string) | | | +| gameplay_admission_allowed | [bool](#bool) | | | +| membership_version | [GetTenantMembershipForRuntimeResponse.MembershipVersionEntry](#account-v1-GetTenantMembershipForRuntimeResponse-MembershipVersionEntry) | repeated | | +| evaluated_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| membership_exists | [bool](#bool) | | | +| membership_lifecycle_state | [string](#string) | | | +| membership_authority_generation | [string](#string) | | | +| authority_tuple | [RuntimeAuthorityTuple](#account-v1-RuntimeAuthorityTuple) | | | +| issuance_fence | [string](#string) | | | +| outbox_checkpoints | [RuntimeOutboxCheckpoint](#account-v1-RuntimeOutboxCheckpoint) | repeated | | +| outbox_source_evidence | [RuntimeOutboxSourceEvidence](#account-v1-RuntimeOutboxSourceEvidence) | repeated | | +| roles | [string](#string) | repeated | | +| membership_baseline | [RuntimeMembershipBaseline](#account-v1-RuntimeMembershipBaseline) | | | +| request_account_id | [string](#string) | | Exact canonical UUID echo of player_context.account_id. | +| request_tenant_id | [string](#string) | | Exact canonical UUID echo of player_context.tenant_id. | +| request_id | [string](#string) | | | +| authority_availability | [string](#string) | | | - + -### UpdateProfileResponse +### GetTenantMembershipForRuntimeResponse.MembershipVersionEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| key | [string](#string) | | | +| value | [string](#string) | | | - - -### VerifyEmailRequest + +### IssueDirectTextConnectScopeRequest +Game Session supplies its authenticated, transport-local player context and +exact catalog/pointer evidence. Account re-resolves the target before issuance. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| player_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | | | tenant_id | [string](#string) | | | -| token | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| catalog_revision | [int64](#int64) | | | +| pointer_version | [int64](#int64) | | | - + -### VerifyEmailResponse +### IssueDirectTextConnectScopeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| connect_scope_id | [string](#string) | | | +| connect_scope_expires_at | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - + - +### JoinPublicProductionMembershipRequest - -### AccountService +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| player_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | | +| connect_scope_id | [string](#string) | | | +| request_id | [string](#string) | | | -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#account-v1-PingRequest) | [PingResponse](#account-v1-PingResponse) | | -| CreateAccount | [CreateAccountRequest](#account-v1-CreateAccountRequest) | [CreateAccountResponse](#account-v1-CreateAccountResponse) | | -| Authenticate | [AuthenticateRequest](#account-v1-AuthenticateRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | -| GetProfile | [GetProfileRequest](#account-v1-GetProfileRequest) | [GetProfileResponse](#account-v1-GetProfileResponse) | | -| UpdateProfile | [UpdateProfileRequest](#account-v1-UpdateProfileRequest) | [UpdateProfileResponse](#account-v1-UpdateProfileResponse) | | -| ExportAccount | [ExportAccountRequest](#account-v1-ExportAccountRequest) | [ExportAccountResponse](#account-v1-ExportAccountResponse) | | -| DeleteAccount | [DeleteAccountRequest](#account-v1-DeleteAccountRequest) | [DeleteAccountResponse](#account-v1-DeleteAccountResponse) | | -| RequestPasswordReset | [RequestPasswordResetRequest](#account-v1-RequestPasswordResetRequest) | [RequestPasswordResetResponse](#account-v1-RequestPasswordResetResponse) | | -| CompletePasswordReset | [CompletePasswordResetRequest](#account-v1-CompletePasswordResetRequest) | [CompletePasswordResetResponse](#account-v1-CompletePasswordResetResponse) | | -| LinkExternalAccount | [LinkExternalAccountRequest](#account-v1-LinkExternalAccountRequest) | [LinkExternalAccountResponse](#account-v1-LinkExternalAccountResponse) | | -| RequestEmailVerification | [RequestEmailVerificationRequest](#account-v1-RequestEmailVerificationRequest) | [RequestEmailVerificationResponse](#account-v1-RequestEmailVerificationResponse) | | -| VerifyEmail | [VerifyEmailRequest](#account-v1-VerifyEmailRequest) | [VerifyEmailResponse](#account-v1-VerifyEmailResponse) | | - - -

Top

+ -## account/v1/notification_service.proto +### JoinPublicProductionMembershipResponse - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| outcome_code | [string](#string) | | | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| membership_id | [string](#string) | | | +| membership_version | [int64](#int64) | | | +| membership_authority_generation | [int64](#int64) | | | +| replayed | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + -### SendNotificationRequest + + + + + + +### LinkExternalAccountRequest @@ -752,16 +1167,17 @@ Basic ping response containing a greeting and optional error details. | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | account_id | [string](#string) | | | -| message | [string](#string) | | | +| provider | [string](#string) | | | +| external_id | [string](#string) | | | - + -### SendNotificationResponse +### LinkExternalAccountResponse @@ -774,94 +1190,105 @@ Basic ping response containing a greeting and optional error details. - - + - +### ListPresenceVisibilityPoliciesRequest +Internal bounded bulk read used by Social Groups when projecting friend presence. - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_ids | [string](#string) | repeated | | -### NotificationService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| SendNotification | [SendNotificationRequest](#account-v1-SendNotificationRequest) | [SendNotificationResponse](#account-v1-SendNotificationResponse) | | - + - -

Top

+### ListPresenceVisibilityPoliciesResponse -## account/v1/payment_service.proto + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| policies | [PresenceVisibilityPolicyEntry](#account-v1-PresenceVisibilityPolicyEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### CreateDonationRequest + + + + +### PingRequest +Empty request used to verify that the service is reachable. + + + + + +### PingResponse +Basic ping response containing a greeting and optional error details. + + | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| amount_cents | [int64](#int64) | | | +| message | [string](#string) | | Message describing the current status of the service. | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | Populated on application-level failure conditions. | - + -### CreateDonationResponse +### PresenceVisibilityPolicyEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| intent_id | [string](#string) | | | -| client_secret | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| account_id | [string](#string) | | | +| policy | [string](#string) | | | - + -### CreatePaymentIntentRequest +### RequestEmailLoginOtpRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| amount_cents | [int64](#int64) | | | +| email | [string](#string) | | | - + -### CreatePaymentIntentResponse +### RequestEmailLoginOtpResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| intent_id | [string](#string) | | | -| client_secret | [string](#string) | | | +| accepted | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -869,32 +1296,30 @@ Basic ping response containing a greeting and optional error details. - + -### CreateSubscriptionRequest +### RequestEmailVerificationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | -| plan_id | [string](#string) | | | - + -### CreateSubscriptionResponse +### RequestEmailVerificationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| subscription_id | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -902,25 +1327,24 @@ Basic ping response containing a greeting and optional error details. - + -### RefundPaymentRequest +### RequestPasswordResetRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| payment_id | [string](#string) | | | +| email | [string](#string) | | | - + -### RefundPaymentResponse +### RequestPasswordResetResponse @@ -933,262 +1357,239 @@ Basic ping response containing a greeting and optional error details. - - + - +### RuntimeAccountSecurityCutoff - -### PaymentService +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_authority_generation | [string](#string) | | | +| outbox_stream_key | [string](#string) | | | +| outbox_sequence | [string](#string) | | | -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| CreatePaymentIntent | [CreatePaymentIntentRequest](#account-v1-CreatePaymentIntentRequest) | [CreatePaymentIntentResponse](#account-v1-CreatePaymentIntentResponse) | | -| CreateSubscription | [CreateSubscriptionRequest](#account-v1-CreateSubscriptionRequest) | [CreateSubscriptionResponse](#account-v1-CreateSubscriptionResponse) | | -| CreateDonation | [CreateDonationRequest](#account-v1-CreateDonationRequest) | [CreateDonationResponse](#account-v1-CreateDonationResponse) | | -| RefundPayment | [RefundPaymentRequest](#account-v1-RefundPaymentRequest) | [RefundPaymentResponse](#account-v1-RefundPaymentResponse) | | - - -

Top

+ -## account/v1/virtual_currency_service.proto - - - - - -### AddCurrencyRequest +### RuntimeAuthorityTuple | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| currency_code | [string](#string) | | | -| amount | [int64](#int64) | | | +| issuer_auth_generation | [string](#string) | | | +| account_authority_generation | [string](#string) | | | +| tenant_authority_generation | [RuntimeAuthorityTuple.TenantAuthorityGenerationEntry](#account-v1-RuntimeAuthorityTuple-TenantAuthorityGenerationEntry) | repeated | | +| membership_authority_generation | [RuntimeAuthorityTuple.MembershipAuthorityGenerationEntry](#account-v1-RuntimeAuthorityTuple-MembershipAuthorityGenerationEntry) | repeated | | +| private_realm_grant_versions | [RuntimePrivateRealmGrantVersion](#account-v1-RuntimePrivateRealmGrantVersion) | repeated | | +| account_security_cutoff | [RuntimeAccountSecurityCutoff](#account-v1-RuntimeAccountSecurityCutoff) | | | +| tenant_billing_cutoff | [RuntimeTenantBillingCutoffMap](#account-v1-RuntimeTenantBillingCutoffMap) | | | - + -### AddCurrencyResponse +### RuntimeAuthorityTuple.MembershipAuthorityGenerationEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| balance | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| key | [string](#string) | | | +| value | [string](#string) | | | - + -### GetBalanceRequest +### RuntimeAuthorityTuple.TenantAuthorityGenerationEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| currency_code | [string](#string) | | | +| key | [string](#string) | | | +| value | [string](#string) | | | - + -### GetBalanceResponse +### RuntimeMembershipBaseline | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| balance | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| membership_lifecycle_state | [string](#string) | | | +| membership_version | [RuntimeMembershipBaseline.MembershipVersionEntry](#account-v1-RuntimeMembershipBaseline-MembershipVersionEntry) | repeated | | +| membership_authority_generation | [string](#string) | | | - + -### SpendCurrencyRequest +### RuntimeMembershipBaseline.MembershipVersionEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| currency_code | [string](#string) | | | -| amount | [int64](#int64) | | | +| key | [string](#string) | | | +| value | [string](#string) | | | - + -### SpendCurrencyResponse +### RuntimeOutboxCheckpoint | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| balance | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - +| outbox_stream_key | [string](#string) | | | +| outbox_sequence | [string](#string) | | | - - - + - - -### VirtualCurrencyService - +### RuntimeOutboxSourceEvidence -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| GetBalance | [GetBalanceRequest](#account-v1-GetBalanceRequest) | [GetBalanceResponse](#account-v1-GetBalanceResponse) | | -| AddCurrency | [AddCurrencyRequest](#account-v1-AddCurrencyRequest) | [AddCurrencyResponse](#account-v1-AddCurrencyResponse) | | -| SpendCurrency | [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) | [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) | | - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| outbox_stream_key | [string](#string) | | | +| outbox_sequence | [string](#string) | | | +| event_id | [string](#string) | | | +| event_digest | [string](#string) | | | +| canonical_event_json | [string](#string) | | Exact canonical Account event bytes, carried separately from its two-field checkpoint. | - -

Top

-## automation-scripting/v1/automation_scripting_service.proto - + -### AddFormationMemberRequest +### RuntimePrivateRealmGrantVersion | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| formation_id | [string](#string) | | | -| npc_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| playtest_lifecycle_id | [string](#string) | | | +| grant_version | [string](#string) | | | - + -### AddFormationMemberResponse +### RuntimeTenantBillingCutoff | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_authority_generation | [string](#string) | | | +| tenant_billing_sequence | [string](#string) | | | +| outbox_stream_key | [string](#string) | | | +| outbox_sequence | [string](#string) | | | - + -### CancelPendingWorkItemsForPatchRequest +### RuntimeTenantBillingCutoffEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| cutoff | [RuntimeTenantBillingCutoff](#account-v1-RuntimeTenantBillingCutoff) | | | - + -### CancelPendingWorkItemsForPatchResponse +### RuntimeTenantBillingCutoffMap | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| canceled_count | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| entries | [RuntimeTenantBillingCutoffEntry](#account-v1-RuntimeTenantBillingCutoffEntry) | repeated | | - + -### CreateFormationRequest +### UpdateProfileRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| leader_npc_id | [string](#string) | | | -| formation_type | [string](#string) | | LINE, WEDGE, CIRCLE | +| account_id | [string](#string) | | Canonical non-nil Account UUID, exactly matching the authenticated caller subject. | +| profile_json | [string](#string) | | | - + -### CreateFormationResponse +### UpdateProfileResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| formation_id | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1196,207 +1597,209 @@ Basic ping response containing a greeting and optional error details. - + -### DisablePluginRequest +### VerifyEmailLoginOtpRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| email | [string](#string) | | | +| code | [string](#string) | | | - + -### DisablePluginResponse +### VerifyEmailRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| token | [string](#string) | | | - + -### DrainPluginRequest +### VerifyEmailResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | - - +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### DrainPluginResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### AccountService - -### GetPluginStatusRequest +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#account-v1-PingRequest) | [PingResponse](#account-v1-PingResponse) | | +| CreateAccount | [CreateAccountRequest](#account-v1-CreateAccountRequest) | [CreateAccountResponse](#account-v1-CreateAccountResponse) | | +| Authenticate | [AuthenticateRequest](#account-v1-AuthenticateRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | +| RequestEmailLoginOtp | [RequestEmailLoginOtpRequest](#account-v1-RequestEmailLoginOtpRequest) | [RequestEmailLoginOtpResponse](#account-v1-RequestEmailLoginOtpResponse) | | +| VerifyEmailLoginOtp | [VerifyEmailLoginOtpRequest](#account-v1-VerifyEmailLoginOtpRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | +| GetTenantMembershipForRuntime | [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) | [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) | | +| GetRealmAccessGrantForRuntime | [GetRealmAccessGrantForRuntimeRequest](#account-v1-GetRealmAccessGrantForRuntimeRequest) | [GetRealmAccessGrantForRuntimeResponse](#account-v1-GetRealmAccessGrantForRuntimeResponse) | | +| GetTenantEntitlementsForRuntime | [GetTenantEntitlementsForRuntimeRequest](#account-v1-GetTenantEntitlementsForRuntimeRequest) | [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) | | +| IssueDirectTextConnectScope | [IssueDirectTextConnectScopeRequest](#account-v1-IssueDirectTextConnectScopeRequest) | [IssueDirectTextConnectScopeResponse](#account-v1-IssueDirectTextConnectScopeResponse) | | +| JoinPublicProductionMembership | [JoinPublicProductionMembershipRequest](#account-v1-JoinPublicProductionMembershipRequest) | [JoinPublicProductionMembershipResponse](#account-v1-JoinPublicProductionMembershipResponse) | | +| GetProfile | [GetProfileRequest](#account-v1-GetProfileRequest) | [GetProfileResponse](#account-v1-GetProfileResponse) | | +| ListPresenceVisibilityPolicies | [ListPresenceVisibilityPoliciesRequest](#account-v1-ListPresenceVisibilityPoliciesRequest) | [ListPresenceVisibilityPoliciesResponse](#account-v1-ListPresenceVisibilityPoliciesResponse) | | +| UpdateProfile | [UpdateProfileRequest](#account-v1-UpdateProfileRequest) | [UpdateProfileResponse](#account-v1-UpdateProfileResponse) | | +| ExportAccount | [ExportAccountRequest](#account-v1-ExportAccountRequest) | [ExportAccountResponse](#account-v1-ExportAccountResponse) | | +| ExportTenantData | [ExportTenantDataRequest](#account-v1-ExportTenantDataRequest) | [ExportTenantDataResponse](#account-v1-ExportTenantDataResponse) | | +| DeleteAccount | [DeleteAccountRequest](#account-v1-DeleteAccountRequest) | [DeleteAccountResponse](#account-v1-DeleteAccountResponse) | | +| RequestPasswordReset | [RequestPasswordResetRequest](#account-v1-RequestPasswordResetRequest) | [RequestPasswordResetResponse](#account-v1-RequestPasswordResetResponse) | | +| CompletePasswordReset | [CompletePasswordResetRequest](#account-v1-CompletePasswordResetRequest) | [CompletePasswordResetResponse](#account-v1-CompletePasswordResetResponse) | | +| LinkExternalAccount | [LinkExternalAccountRequest](#account-v1-LinkExternalAccountRequest) | [LinkExternalAccountResponse](#account-v1-LinkExternalAccountResponse) | | +| RequestEmailVerification | [RequestEmailVerificationRequest](#account-v1-RequestEmailVerificationRequest) | [RequestEmailVerificationResponse](#account-v1-RequestEmailVerificationResponse) | | +| VerifyEmail | [VerifyEmailRequest](#account-v1-VerifyEmailRequest) | [VerifyEmailResponse](#account-v1-VerifyEmailResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | + +

Top

+## account/v1/issuer_authority_service.proto - + -### GetPluginStatusResponse +### IssuerAuthoritySourceSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| active_plugin_version_id | [string](#string) | | | -| pending_plugin_version_id | [string](#string) | | | -| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| issuer_id | [string](#string) | | | +| source_scope | [string](#string) | | | +| outbox_stream_key | [string](#string) | | | +| issuer_auth_generation | [string](#string) | | | +| source_version | [string](#string) | | | +| outbox_sequence | [string](#string) | | | +| latest_event_canonical_json | [string](#string) | optional | Must be absent at sequence zero, present and exact at positive sequence. | - + -### GetScriptPatchStatusRequest +### ReadIssuerAuthorityForRuntimeRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | +| issuer_id | [string](#string) | | | +| request_id | [string](#string) | | | +| requested_outbox_sequence | [string](#string) | optional | Omit for current source evidence; when present, must be canonical positive. | - + -### GetScriptPatchStatusResponse +### ReadIssuerAuthorityForRuntimeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - +| schema_version | [string](#string) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| source_snapshot | [IssuerAuthoritySourceSnapshot](#account-v1-IssuerAuthoritySourceSnapshot) | | | +| requested_event_canonical_json | [string](#string) | optional | Present exactly when the request selected a positive historical sequence. | - - -### GetScriptStatusRequest - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_name | [string](#string) | | | + - +### IssuerAuthorityService +Owner-local source evidence only; this service is not wired for runtime use. +Caller and response workload identities must both be verified from mTLS. -### GetScriptStatusResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadIssuerAuthorityForRuntime | [ReadIssuerAuthorityForRuntimeRequest](#account-v1-ReadIssuerAuthorityForRuntimeRequest) | [ReadIssuerAuthorityForRuntimeResponse](#account-v1-ReadIssuerAuthorityForRuntimeResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| queued | [bool](#bool) | | | -| running | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## account/v1/notification_service.proto - + -### ListFormationMembersRequest +### SendNotificationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| formation_id | [string](#string) | | | +| account_id | [string](#string) | | | +| message | [string](#string) | | | - + -### ListFormationMembersResponse +### SendNotificationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| npc_ids | [string](#string) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1404,66 +1807,59 @@ Basic ping response containing a greeting and optional error details. - - -### ListScriptPatchStatusesRequest - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | + +### NotificationService - -### ListScriptPatchStatusesResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| SendNotification | [SendNotificationRequest](#account-v1-SendNotificationRequest) | [SendNotificationResponse](#account-v1-SendNotificationResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| patches | [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## account/v1/payment_service.proto - + -### NotifyScriptVersionUpdateRequest +### CreateDonationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| affected_scripts | [string](#string) | repeated | | +| account_id | [string](#string) | | | +| amount_cents | [int64](#int64) | | | - + -### NotifyScriptVersionUpdateResponse +### CreateDonationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| intent_id | [string](#string) | | | +| client_secret | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1471,25 +1867,33 @@ Basic ping response containing a greeting and optional error details. - + -### PingRequest +### CreatePaymentIntentRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| amount_cents | [int64](#int64) | | | - -### PingResponse + + + +### CreatePaymentIntentResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| intent_id | [string](#string) | | | +| client_secret | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1497,7 +1901,1662 @@ Basic ping response containing a greeting and optional error details. - + + +### CreateSubscriptionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| plan_id | [string](#string) | | | + + + + + + + + +### CreateSubscriptionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| subscription_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RefundPaymentRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| payment_id | [string](#string) | | | + + + + + + + + +### RefundPaymentResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + + + + + + + +### PaymentService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| CreatePaymentIntent | [CreatePaymentIntentRequest](#account-v1-CreatePaymentIntentRequest) | [CreatePaymentIntentResponse](#account-v1-CreatePaymentIntentResponse) | | +| CreateSubscription | [CreateSubscriptionRequest](#account-v1-CreateSubscriptionRequest) | [CreateSubscriptionResponse](#account-v1-CreateSubscriptionResponse) | | +| CreateDonation | [CreateDonationRequest](#account-v1-CreateDonationRequest) | [CreateDonationResponse](#account-v1-CreateDonationResponse) | | +| RefundPayment | [RefundPaymentRequest](#account-v1-RefundPaymentRequest) | [RefundPaymentResponse](#account-v1-RefundPaymentResponse) | | + + + + + + +

Top

+ +## account/v1/virtual_currency_service.proto + + + + + +### AddCurrencyRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| currency_code | [string](#string) | | | +| amount | [int64](#int64) | | | + + + + + + + + +### AddCurrencyResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| balance | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetBalanceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| currency_code | [string](#string) | | | + + + + + + + + +### GetBalanceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| balance | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### SpendCurrencyRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| currency_code | [string](#string) | | | +| amount | [int64](#int64) | | | + + + + + + + + +### SpendCurrencyResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| balance | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + + + + + + + +### VirtualCurrencyService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetBalance | [GetBalanceRequest](#account-v1-GetBalanceRequest) | [GetBalanceResponse](#account-v1-GetBalanceResponse) | | +| AddCurrency | [AddCurrencyRequest](#account-v1-AddCurrencyRequest) | [AddCurrencyResponse](#account-v1-AddCurrencyResponse) | | +| SpendCurrency | [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) | [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) | | + + + + + + +

Top

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

Top

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

Top

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

Top

+ +## game-design/v1/tenant_identity_service.proto + + + + + +### GameSessionTenantAssociationManifestEvidence + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| operation_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| signer_key_id | [string](#string) | | | +| approved_by | [string](#string) | | | +| approval_reference | [string](#string) | | | +| signed_at | [string](#string) | | | +| legacy_game_session_tenant_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| source_game_row_id | [string](#string) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| game_session_evidence_digest | [string](#string) | | | + + + + + + + + +### ResolveAuthoredWorldSourceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | + + + + + + + + +### ResolveAuthoredWorldSourceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| registration_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| tenant_slug | [string](#string) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + + + + + + + + +### ResolveFreshTenantCreationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| creation_request_id | [string](#string) | | | +| expected_request_digest | [string](#string) | | | + + + + + + + + +### ResolveFreshTenantCreationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| creation_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + + + + + + + + +### ResolveLegacyAccountTenantAssociationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| legacy_account_tenant_id | [int64](#int64) | | | + + + + + + + + +### ResolveLegacyAccountTenantAssociationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| legacy_account_tenant_id | [int64](#int64) | | | +| source_legacy_game_tenant_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| account_evidence_digest | [string](#string) | | | +| operation_id | [string](#string) | | | +| manifest_digest | [string](#string) | | | +| target_namespace | [string](#string) | | | +| signer_key_id | [string](#string) | | | +| approved_by | [string](#string) | | | +| approval_reference | [string](#string) | | | +| signed_at | [string](#string) | | | +| operation_entry_count | [int32](#int32) | | | +| manifest_signature | [string](#string) | | | +| manifest_schema_version | [int32](#int32) | | | + + + + + + + + +### ResolveLegacyGameSessionTenantAssociationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| legacy_game_session_tenant_id | [string](#string) | | Canonical positive decimal BIGINT provenance, not a public tenant identifier. | + + + + + + + + +### ResolveLegacyGameSessionTenantAssociationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| manifest | [GameSessionTenantAssociationManifestEvidence](#gamedesign-v1-GameSessionTenantAssociationManifestEvidence) | | | +| manifest_digest | [string](#string) | | | +| ed25519_signature | [string](#string) | | | + + + + + + + + +### ResolveLegacyGameTenantIdentityRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| legacy_game_tenant_id | [string](#string) | | | + + + + + + + + +### ResolveLegacyGameTenantIdentityResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_tenant_id | [string](#string) | | | +| source_legacy_game_tenant_id | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| provenance_kind | [string](#string) | | | + + + + + + + + +### ResolveRuntimeTenantIdentityRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_tenant_id | [string](#string) | | | +| request_id | [string](#string) | | | + + + + + + + + +### ResolveRuntimeTenantIdentityResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | + + + + + + + + + + + + + + +### TenantIdentityService +Owner-local legacy source read. This does not attest an Account numeric tenant key. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolveLegacyGameTenantIdentity | [ResolveLegacyGameTenantIdentityRequest](#gamedesign-v1-ResolveLegacyGameTenantIdentityRequest) | [ResolveLegacyGameTenantIdentityResponse](#gamedesign-v1-ResolveLegacyGameTenantIdentityResponse) | | +| ResolveLegacyAccountTenantAssociation | [ResolveLegacyAccountTenantAssociationRequest](#gamedesign-v1-ResolveLegacyAccountTenantAssociationRequest) | [ResolveLegacyAccountTenantAssociationResponse](#gamedesign-v1-ResolveLegacyAccountTenantAssociationResponse) | Owner-approved cross-service legacy association; Account is the sole caller. | +| ResolveFreshTenantCreation | [ResolveFreshTenantCreationRequest](#gamedesign-v1-ResolveFreshTenantCreationRequest) | [ResolveFreshTenantCreationResponse](#gamedesign-v1-ResolveFreshTenantCreationResponse) | Exact immutable readback of a newly created tenant operation for Account. | +| ResolveRuntimeTenantIdentity | [ResolveRuntimeTenantIdentityRequest](#gamedesign-v1-ResolveRuntimeTenantIdentityRequest) | [ResolveRuntimeTenantIdentityResponse](#gamedesign-v1-ResolveRuntimeTenantIdentityResponse) | Exact owner-local read of one persisted runtime tenant identity for Game Session. | +| ResolveAuthoredWorldSource | [ResolveAuthoredWorldSourceRequest](#gamedesign-v1-ResolveAuthoredWorldSourceRequest) | [ResolveAuthoredWorldSourceResponse](#gamedesign-v1-ResolveAuthoredWorldSourceResponse) | Exact immutable authored-selector source for Game Session; not catalog enrollment. | +| ResolveLegacyGameSessionTenantAssociation | [ResolveLegacyGameSessionTenantAssociationRequest](#gamedesign-v1-ResolveLegacyGameSessionTenantAssociationRequest) | [ResolveLegacyGameSessionTenantAssociationResponse](#gamedesign-v1-ResolveLegacyGameSessionTenantAssociationResponse) | Exact audited retained Game Session association; never an Account manifest or admission. | + + + + + + +

Top

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

Top

+ +## game-session/v1/game_session_service.proto + + + + + +### AccountPresenceEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| online | [bool](#bool) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| character_name | [string](#string) | | | +| activity_state | [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) | | | +| last_seen_at_ms | [int64](#int64) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| recent_disposition | [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) | | | +| pointer_version | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### AdmissionPointerControlPlaneEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| visible | [bool](#bool) | | | +| requires_character_selection | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| occurred_at_ms | [int64](#int64) | | | +| prepared_version_upgrade_id | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | + + + + + + + + +### CutoverParticipantResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| participant | [string](#string) | | | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | + + + + + + + + +### EnqueueAutomationCommandIfAbsentRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| binding_id | [string](#string) | | Stable handler binding identity assigned by the cross-service contract. | +| script_pin_epoch | [int64](#int64) | | Exact script pin evidence captured by Automation. The Game Session owner/admission boundary compares the complete three-field tuple (script_patch_version, script_pin_epoch, and script_pin_control_plane_request_id) with its authoritative current tuple before staging or replaying; a mismatched request ID is rejected owner evidence, not a distinct claim. | +| script_pin_control_plane_request_id | [string](#string) | | | +| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | + + + + + + + + +### EnqueueAutomationCommandIfAbsentResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| admission_outcome | [string](#string) | | | +| command_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### EnqueueCommandRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | +| command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | + + + + + + + + +### EnqueueCommandResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| command_id | [string](#string) | | | + + + + + + + + +### ExecutePreparedVersionCutoverRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| tenant_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| prepared_version_upgrade_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_pointer_version | [int64](#int64) | optional | | + + + + + + + + +### ExecutePreparedVersionCutoverResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ExpectedCurrentPin + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| kind | [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GameInstanceRuntimeState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| runtime_version_id | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| status | [string](#string) | | | +| version_id | [string](#string) | | | +| release_bundle_id | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| script_patch_pinned_at_ms | [int64](#int64) | | | +| script_patch_pinned_by | [string](#string) | | | +| script_patch_pinned_reason | [string](#string) | | | +| script_patch_pinned_control_plane_request_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| current_admission_pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| script_pin_epoch | [int64](#int64) | | Monotonic script-pin generation. It fences same-version repins. | +| pinned_script_patch_base_version_id | [int64](#int64) | | Base version captured and stored when this script patch was admitted. Zero means legacy or otherwise unknown provenance; readers must not substitute the current runtime version. | + + + + + + + + +### GameplayAdmissionPointer + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| requires_character_selection | [bool](#bool) | | | +| visible | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | + + + + + + + + +### GameplayCommandStatus + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| command_name | [string](#string) | | | +| sanitized_command_text | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| accepted_at_ms | [int64](#int64) | | | +| staged_at_ms | [int64](#int64) | | | +| completed_at_ms | [int64](#int64) | | | +| last_attempt_at_ms | [int64](#int64) | | | +| attempt_count | [int32](#int32) | | | +| failure_code | [string](#string) | | Canonical structured terminal-reason code. For rollback purge this is ROLLBACK_PURGED and must be returned with failure_message. | +| failure_message | [string](#string) | | Canonical structured terminal-reason message. Required with failure_code when a terminal reason applies, including rollback purge. | +| source_type | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| enqueue_seq | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| remote_coordinator_id | [string](#string) | | | +| remote_followup_id | [string](#string) | | | +| remote_state | [string](#string) | | | +| remote_result_outcome | [string](#string) | | | +| remote_result_payload_json | [string](#string) | | | +| remote_result_observed_at_ms | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| remote_result_command_id | [string](#string) | | | +| remote_result_error_code | [string](#string) | | | +| remote_result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| remote_origin_game_instance_id | [string](#string) | | | +| remote_origin_region_id | [string](#string) | | | +| remote_origin_region_epoch | [int64](#int64) | | | +| remote_target_game_instance_id | [string](#string) | | | +| remote_target_region_id | [string](#string) | | | +| remote_target_region_epoch | [int64](#int64) | | | +| remote_origin_deadline_region_epoch | [int64](#int64) | | | +| remote_origin_deadline_tick_id | [int64](#int64) | | | +| remote_late_result_policy | [string](#string) | | | +| remote_target_command_execution_outcome | [string](#string) | | | +| remote_target_command_gameplay_result | [string](#string) | | | +| remote_followup_status | [string](#string) | | | +| remote_followup_payload_kind | [string](#string) | | | +| remote_followup_requested_command | [string](#string) | | | +| remote_followup_requires_solo_tick | [bool](#bool) | | | +| remote_followup_origin_source_kind | [string](#string) | | | +| remote_followup_origin_source_state | [string](#string) | | | +| remote_followup_origin_source_ordinal | [int64](#int64) | | | +| remote_followup_origin_source_due_tick_id | [int64](#int64) | | | +| remote_followup_origin_source_due_at_ms | [int64](#int64) | | | +| remote_target_entity_id | [string](#string) | | | +| remote_followup_effect_key | [string](#string) | | | +| remote_followup_failure_code | [string](#string) | | | +| remote_followup_failure_message | [string](#string) | | | +| remote_followup_event_type | [string](#string) | | | +| remote_followup_event_schema_version | [string](#string) | | | +| remote_followup_script_event_id | [string](#string) | | | +| remote_followup_trigger_mode | [string](#string) | | | +| remote_followup_claim_target_aggregate | [string](#string) | | | +| current_runtime_region_id | [string](#string) | | | +| current_runtime_region_epoch | [int64](#int64) | | | +| current_runtime_game_instance_id | [string](#string) | | | +| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_runtime_world_slug | [string](#string) | | | +| current_runtime_realm_slug | [string](#string) | | | +| current_runtime_pointer_version | [int64](#int64) | | | +| is_current_runtime_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### GameplayRealm + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| requires_character_selection | [bool](#bool) | | | +| visible | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | + + + + + + + + +### GameplayWorld + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| display_name | [string](#string) | | | + + + + + + + + +### GetAdmissionPointerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| realm_slug | [string](#string) | | | +| world_slug | [string](#string) | | | + + + + + + + + +### GetAdmissionPointerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| admission_pointer | [GameplayAdmissionPointer](#game_session-v1-GameplayAdmissionPointer) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetGameInstanceRuntimeStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | + + + + + + + + +### GetGameInstanceRuntimeStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| runtime_state | [GameInstanceRuntimeState](#game_session-v1-GameInstanceRuntimeState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetGameSessionPinConvergenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | + + + + + + + + +### GetGameSessionPinConvergenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| observed_pinned_script_patch_version | [string](#string) | | | +| last_observed_control_plane_request_id | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| is_stale | [bool](#bool) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| observed_script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GetGameplayCommandStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | + + + + + + + + +### GetGameplayCommandStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command | [GameplayCommandStatus](#game_session-v1-GameplayCommandStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetPinnedScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | + + + + + + + + +### GetPinnedScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pinned_script_patch_version | [string](#string) | | | +| pinned_at_ms | [int64](#int64) | | | +| pinned_by | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GetPreparedVersionUpgradeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| preparation_id | [string](#string) | | | + + + + + + + + +### GetPreparedVersionUpgradeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteCommandCoordinatorRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | + + + + + + + + +### GetRemoteCommandCoordinatorResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteFollowupRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| followup_id | [string](#string) | | | + + + + + + + + +### GetRemoteFollowupResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followup | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteFollowupResultRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| result_id | [string](#string) | | | + + + + + + + + +### GetRemoteFollowupResultResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRuntimeOwnershipStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | + + + + + + + + +### GetRuntimeOwnershipStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| ownership | [RuntimeOwnershipStatus](#game_session-v1-RuntimeOwnershipStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetTickStatusRequest + + + + + + + + + +### GetTickStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| status | [TickStatus](#game_session-v1-TickStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListAdmissionPointerAuditRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | + + + + + + + + +### ListAdmissionPointerAuditResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| audit | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListAdmissionPointersRequest + + + + + + + + + +### ListAdmissionPointersResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListGameplayRealmsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | + + + + + + + + +### ListGameplayRealmsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| realms | [GameplayRealm](#game_session-v1-GameplayRealm) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListGameplayWorldsRequest + + + + + + + + + +### ListGameplayWorldsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| worlds | [GameplayWorld](#game_session-v1-GameplayWorld) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteCommandCoordinatorsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| state | [string](#string) | | | +| followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| followup_status | [string](#string) | | | +| followup_claimed_tick_batch_id | [string](#string) | | | +| followup_requires_solo_tick | [bool](#bool) | | | +| followup_origin_source_state | [string](#string) | | | +| latest_result_outcome | [string](#string) | | | +| latest_result_error_code | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| followup_queue_source_kind | [string](#string) | | | +| followup_queue_source_state | [string](#string) | | | +| followup_queue_source_ordinal | [int64](#int64) | | | +| followup_queue_source_due_tick_id | [int64](#int64) | | | +| followup_queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteCommandCoordinatorsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinators | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteFollowupResultsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| outcome | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_game_instance_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| result_error_code | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| result_command_id | [string](#string) | | | +| result_command_execution_outcome | [string](#string) | | | +| result_command_gameplay_result | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| failure_code | [string](#string) | | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| result_message | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_state | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteFollowupResultsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| results | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteFollowupsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| status | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| failure_code | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| requested_command | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteFollowupsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followups | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PauseTicksForScopeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### PauseTicksForScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PauseTicksRequest +Administrative request to pause tick execution. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reason | [string](#string) | | | + + + + + + + + +### PauseTicksResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PluginPublicationLink + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| plugin_version_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | + + + + + + + + +### PrepareVersionUpgradeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | + + + + + + + + +### PrepareVersionUpgradeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PreparedVersionUpgrade + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| source_version_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| target_launch_descriptor_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | +| checked_participants | [string](#string) | repeated | | +| checked_at_ms | [int64](#int64) | | | +| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | +| control_plane_request_id | [string](#string) | | | +| executed_target_game_instance_id | [string](#string) | | | +| executed_pointer_version | [int64](#int64) | | | +| executed_at_ms | [int64](#int64) | | | +| execution_control_plane_request_id | [string](#string) | | | - + -### SetPluginActiveVersionRequest +### PurgeQueuedTickCommandsForPluginVersionRequest @@ -1525,28 +9238,27 @@ Basic ping response containing a greeting and optional error details. | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | | plugin_id | [string](#string) | | | -| target_plugin_version_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | | control_plane_request_id | [string](#string) | | | | actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | - + -### SetPluginActiveVersionResponse +### PurgeQueuedTickCommandsForPluginVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_plugin_version_id | [string](#string) | | | -| active_plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | +| purged_count | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1554,9 +9266,9 @@ Basic ping response containing a greeting and optional error details. - + -### TriggerScriptEventRequest +### PurgeQueuedTickCommandsForScriptPatchRequest @@ -1565,278 +9277,748 @@ Basic ping response containing a greeting and optional error details. | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | | region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | Required for gameplay/runtime triggers and scheduler triggers so triggers are fenced across scoped coordination resets. External/out-of-band triggers that omit region_epoch must define their own consistency model explicitly. | -| entity_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | + + + + + + + + +### PurgeQueuedTickCommandsForScriptPatchResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| purged_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryAccountPresenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| viewer_account_id | [string](#string) | | | +| account_ids | [string](#string) | repeated | | + + + + + + + + +### QueryAccountPresenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| presences | [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### QueryStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| state_json | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RemoteCommandCoordinatorEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| command_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| target_due_tick_id | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| state | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| updated_at_ms | [int64](#int64) | | | +| followup_status | [string](#string) | | | +| followup_claimed_tick_batch_id | [string](#string) | | | +| latest_result_outcome | [string](#string) | | | +| latest_result_payload_json | [string](#string) | | | +| latest_result_observed_at_ms | [int64](#int64) | | | +| followup_claim_ordinal | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | | script_id | [string](#string) | | | -| plugin_id | [string](#string) | | Plugin identity (required for plugin triggers). For core script triggers, these fields must be absent. | +| followup_payload_kind | [string](#string) | | | +| followup_requested_command | [string](#string) | | | +| latest_result_command_id | [string](#string) | | | +| latest_result_error_code | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| latest_result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| followup_requires_solo_tick | [bool](#bool) | | | +| followup_origin_source_kind | [string](#string) | | | +| followup_origin_source_state | [string](#string) | | | +| followup_origin_source_ordinal | [int64](#int64) | | | +| followup_origin_source_due_tick_id | [int64](#int64) | | | +| followup_origin_source_due_at_ms | [int64](#int64) | | | +| target_entity_id | [string](#string) | | | +| followup_effect_key | [string](#string) | | | +| followup_failure_code | [string](#string) | | | +| followup_failure_message | [string](#string) | | | +| followup_event_type | [string](#string) | | | +| followup_event_schema_version | [string](#string) | | | +| followup_script_event_id | [string](#string) | | | +| followup_trigger_mode | [string](#string) | | | +| followup_read_snapshot_token | [string](#string) | | | +| followup_event_payload_json | [string](#string) | | | +| followup_claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| followup_queue_source_kind | [string](#string) | | | +| followup_queue_source_state | [string](#string) | | | +| followup_queue_source_ordinal | [int64](#int64) | | | +| followup_queue_source_due_tick_id | [int64](#int64) | | | +| followup_queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RemoteFollowupEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followup_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| effect_key | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| status | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| payload_json | [string](#string) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | +| claim_ordinal | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | | plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| command_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requested_command | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | | event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RemoteFollowupResultEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| outcome | [string](#string) | | | +| result_payload_json | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | | script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| command_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| result_command_id | [string](#string) | | | +| result_error_code | [string](#string) | | | +| result_command_execution_outcome | [string](#string) | | | +| result_command_gameplay_result | [string](#string) | | | +| result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | | script_event_id | [string](#string) | | | -| is_dry_run | [bool](#bool) | | | -| trigger_mode | [TriggerMode](#automation_scripting-v1-TriggerMode) | | | -| due_tick_id | [int64](#int64) | | Scheduling context (when applicable). | -| due_at_ms | [int64](#int64) | | | -| payload_json | [string](#string) | | Event payload envelope (implementation-specific). | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RestartSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### RestartSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResumeTicksForScopeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### ResumeTicksForScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResumeTicksRequest +Resume ticks after an authorized maintenance workflow completes. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reason | [string](#string) | | | + + + + + + + + +### ResumeTicksResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### TriggerScriptEventResponse +### RollbackScriptPatchVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| admitted | [bool](#bool) | | Indicates whether the trigger was admitted into the scripting pipeline. This does not imply that commands have been accepted into tick queues; that end-to-end handoff is observable via script_event_audit. | -| admission_outcome | [TriggerAdmissionOutcome](#automation_scripting-v1-TriggerAdmissionOutcome) | | | -| admission_reason | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| target_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | - + -### UpdateScriptRequest +### RollbackScriptPatchVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| version | [string](#string) | | | -| definition | [string](#string) | | | +| previous_script_patch_version | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| previous_script_pin_epoch | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | - + -### UpdateScriptResponse +### RuntimeOwnershipStatus | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| executor_fence | [string](#string) | | | +| owner_service | [string](#string) | | | +| owner_instance_id | [string](#string) | | | +| paused | [bool](#bool) | | | +| last_committed_tick_batch_id | [string](#string) | | | +| updated_at_ms | [int64](#int64) | | | +| last_committed_tick_id | [int64](#int64) | | | +| region_id | [string](#string) | | | +| pending_gameplay_command_count | [int64](#int64) | | | +| due_remote_followup_count | [int64](#int64) | | | +| oldest_due_remote_followup_tick_id | [int64](#int64) | | | +| remote_followup_drain_lag_ms | [int64](#int64) | | | - - -### PluginState + +### ScheduleRemoteFollowupRequest -| Name | Number | Description | -| ---- | ------ | ----------- | -| PLUGIN_STATE_UNSPECIFIED | 0 | | -| PLUGIN_STATE_ENABLED | 1 | | -| PLUGIN_STATE_DISABLED | 2 | | -| PLUGIN_STATE_DRAINING | 3 | | -| PLUGIN_STATE_RELOADING | 4 | | -| PLUGIN_STATE_FAILED | 5 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| command_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| target_due_tick_id | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| followup_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| payload_json | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requested_command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| script_pin_epoch | [int64](#int64) | | Exact source script pin evidence captured by Automation. Game Session must compare this tuple with the authoritative source owner state before accepting the follow-up; the request ID is owner evidence/correlation, not a third pin-identity component. | +| script_pin_control_plane_request_id | [string](#string) | | | +| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | - -### ScriptPatchStatus -| Name | Number | Description | -| ---- | ------ | ----------- | -| SCRIPT_PATCH_STATUS_UNSPECIFIED | 0 | | -| SCRIPT_PATCH_STATUS_READY | 1 | | -| SCRIPT_PATCH_STATUS_FAILED | 2 | | -| SCRIPT_PATCH_STATUS_ROLLED_BACK | 3 | | -| SCRIPT_PATCH_STATUS_PENDING_VALIDATION | 4 | | -| SCRIPT_PATCH_STATUS_ONLOAD_RUNNING | 5 | | + - +### ScheduleRemoteFollowupResponse -### TriggerAdmissionOutcome -| Name | Number | Description | -| ---- | ------ | ----------- | -| TRIGGER_ADMISSION_OUTCOME_UNSPECIFIED | 0 | | -| TRIGGER_ADMISSION_OUTCOME_ADMITTED | 1 | | -| TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_RELOADING | 2 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_QUOTA | 3 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_TENANT_BUDGET | 4 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_DISABLED | 5 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_VERSION_UNAVAILABLE | 6 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_POLICY | 7 | | -| TRIGGER_ADMISSION_OUTCOME_INFRASTRUCTURE_ERROR | 8 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| coordinator_created | [bool](#bool) | | | +| followup_created | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### TriggerMode -| Name | Number | Description | -| ---- | ------ | ----------- | -| TRIGGER_MODE_UNSPECIFIED | 0 | | -| TRIGGER_MODE_NORMAL | 1 | | -| TRIGGER_MODE_CATCH_UP | 2 | | + +### ScriptPatchPublicationLink - - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| script_patch_version | [string](#string) | | | +| version_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | - -### AutomationScriptingControlPlaneService -Operator/control-plane surface for patch lifecycle visibility and rollback support. -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| GetScriptPatchStatus | [GetScriptPatchStatusRequest](#automation_scripting-v1-GetScriptPatchStatusRequest) | [GetScriptPatchStatusResponse](#automation_scripting-v1-GetScriptPatchStatusResponse) | | -| ListScriptPatchStatuses | [ListScriptPatchStatusesRequest](#automation_scripting-v1-ListScriptPatchStatusesRequest) | [ListScriptPatchStatusesResponse](#automation_scripting-v1-ListScriptPatchStatusesResponse) | | -| CancelPendingWorkItemsForPatch | [CancelPendingWorkItemsForPatchRequest](#automation_scripting-v1-CancelPendingWorkItemsForPatchRequest) | [CancelPendingWorkItemsForPatchResponse](#automation_scripting-v1-CancelPendingWorkItemsForPatchResponse) | Cancel pending durable work items for a patch so they are never handed off again. | -| GetPluginStatus | [GetPluginStatusRequest](#automation_scripting-v1-GetPluginStatusRequest) | [GetPluginStatusResponse](#automation_scripting-v1-GetPluginStatusResponse) | Plugin lifecycle/control-plane APIs. | -| SetPluginActiveVersion | [SetPluginActiveVersionRequest](#automation_scripting-v1-SetPluginActiveVersionRequest) | [SetPluginActiveVersionResponse](#automation_scripting-v1-SetPluginActiveVersionResponse) | | -| DisablePlugin | [DisablePluginRequest](#automation_scripting-v1-DisablePluginRequest) | [DisablePluginResponse](#automation_scripting-v1-DisablePluginResponse) | | -| DrainPlugin | [DrainPluginRequest](#automation_scripting-v1-DrainPluginRequest) | [DrainPluginResponse](#automation_scripting-v1-DrainPluginResponse) | | - -### AutomationScriptingService + +### SetAdmissionPointerRequest -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#automation_scripting-v1-PingRequest) | [PingResponse](#automation_scripting-v1-PingResponse) | Simple ping used by health checks | -| TriggerScriptEvent | [TriggerScriptEventRequest](#automation_scripting-v1-TriggerScriptEventRequest) | [TriggerScriptEventResponse](#automation_scripting-v1-TriggerScriptEventResponse) | Deliver a script trigger for evaluation. This RPC is idempotent with respect to Trigger Identity (including script_event_id) and must not evaluate the DSL body more than once for the same identity. | -| CreateFormation | [CreateFormationRequest](#automation_scripting-v1-CreateFormationRequest) | [CreateFormationResponse](#automation_scripting-v1-CreateFormationResponse) | Creates a new NPC formation | -| AddFormationMember | [AddFormationMemberRequest](#automation_scripting-v1-AddFormationMemberRequest) | [AddFormationMemberResponse](#automation_scripting-v1-AddFormationMemberResponse) | Adds an NPC to an existing formation | -| ListFormationMembers | [ListFormationMembersRequest](#automation_scripting-v1-ListFormationMembersRequest) | [ListFormationMembersResponse](#automation_scripting-v1-ListFormationMembersResponse) | Lists all NPCs belonging to a formation | -| UpdateScript | [UpdateScriptRequest](#automation_scripting-v1-UpdateScriptRequest) | [UpdateScriptResponse](#automation_scripting-v1-UpdateScriptResponse) | Uploads or replaces a script definition | -| GetScriptStatus | [GetScriptStatusRequest](#automation_scripting-v1-GetScriptStatusRequest) | [GetScriptStatusResponse](#automation_scripting-v1-GetScriptStatusResponse) | Checks if a script is queued or currently running | -| NotifyScriptVersionUpdate | [NotifyScriptVersionUpdateRequest](#automation_scripting-v1-NotifyScriptVersionUpdateRequest) | [NotifyScriptVersionUpdateResponse](#automation_scripting-v1-NotifyScriptVersionUpdateResponse) | Signals that a new script patch version is available | - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| visible | [bool](#bool) | | | +| requires_character_selection | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_pointer_version | [int64](#int64) | optional | | +| prepared_version_upgrade_id | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | - -

Top

-## entity-management/v1/entity_management_service.proto - + -### Character +### SetAdmissionPointerResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| name | [string](#string) | | | -| level | [int32](#int32) | | | -| experience | [int32](#int32) | | | -| strength | [int32](#int32) | | | -| agility | [int32](#int32) | | | -| intelligence | [int32](#int32) | | | -| stamina | [int32](#int32) | | | -| health | [int32](#int32) | | | -| mana | [int32](#int32) | | | +| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CreateCharacterRequest +### SetPinnedScriptPatchVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| target_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | - + -### CreateCharacterResponse +### SetPinnedScriptPatchVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| character_id | [string](#string) | | | +| previous_script_patch_version | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| previous_script_pin_epoch | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | - + -### GetDraftDesignDigestRequest +### StartSessionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | +| game_template_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| client_ip | [string](#string) | | | +| owner_account_id | [string](#string) | | | - + -### GetDraftDesignDigestResponse +### StartSessionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | +| session_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1844,30 +10026,30 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ListCharactersByAccountRequest +### StopSessionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| account_id | [string](#string) | | | +| session_id | [string](#string) | | | - + -### ListCharactersByAccountResponse +### StopSessionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| characters | [Character](#entity_management-v1-Character) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1875,61 +10057,64 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ListRoomEntitiesRequest +### ToggleFeatureFlagRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| name | [string](#string) | | | +| enabled | [bool](#bool) | | | - + -### ListRoomEntitiesResponse +### ToggleFeatureFlagResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entities | [RoomEntity](#entity_management-v1-RoomEntity) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| entity_snapshot_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | - + -### PingRequest +### ValidateBuiltInCommandAliasRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| alias | [string](#string) | | | - -### PingResponse + + + +### ValidateBuiltInCommandAliasResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| supported | [bool](#bool) | | | +| normalized_alias | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1937,30 +10122,37 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### QueryInventoryRequest +### ValidateInstanceCutoverCompatibilityRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | - + -### QueryInventoryResponse +### ValidateInstanceCutoverCompatibilityResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| item_ids | [string](#string) | repeated | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | +| checked_participants | [string](#string) | repeated | | +| checked_at_ms | [int64](#int64) | | | +| remap_set_id | [string](#string) | | | +| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1968,143 +10160,179 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - - -### RoomEntity - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| display_name | [string](#string) | | | -| entity_type | [EntityType](#entity_management-v1-EntityType) | | | -| role | [string](#string) | | | -| state_flags | [string](#string) | repeated | | -| vision_priority | [int32](#int32) | | | -| reload_hint | [ReloadHint](#entity_management-v1-ReloadHint) | | | -| visible | [bool](#bool) | | | - - + +### AccountPresenceActivityState - -### UpdateEntityRequest +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | + +### AccountRecentPresenceDisposition +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | - + -### UpdateEntityResponse +### CutoverCompatibilityResult +| Name | Number | Description | +| ---- | ------ | ----------- | +| CUTOVER_COMPATIBILITY_RESULT_UNSPECIFIED | 0 | | +| CUTOVER_COMPATIBILITY_RESULT_COMPATIBLE | 1 | | +| CUTOVER_COMPATIBILITY_RESULT_INCOMPATIBLE | 2 | | +| CUTOVER_COMPATIBILITY_RESULT_UNAVAILABLE | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### ExpectedCurrentPin.Kind - +| Name | Number | Description | +| ---- | ------ | ----------- | +| EXPECTED_CURRENT_PIN_KIND_UNSPECIFIED | 0 | | +| EXPECTED_CURRENT_PIN_KIND_UNCONDITIONAL | 1 | | +| EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED | 2 | | +| EXPECTED_CURRENT_PIN_KIND_EXPECT_EPOCH | 3 | | - -### EntityType + + +### TickStatus | Name | Number | Description | | ---- | ------ | ----------- | -| ENTITY_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | -| ITEM | 3 | | +| TICK_STATUS_UNSPECIFIED | 0 | | +| TICK_STATUS_RUNNING | 1 | | +| TICK_STATUS_PAUSED | 2 | | - -### ReloadHint -| Name | Number | Description | -| ---- | ------ | ----------- | -| RELOAD_HINT_UNSPECIFIED | 0 | | -| STABLE | 1 | | -| PLAYER_ENTERED | 2 | | -| PLAYER_LEFT | 3 | | + - +### GameSessionControlPlaneService +Operator/control-plane surface for pinning and rollback of script patch versions, +plus scoped tick pause/resume used for rollback safety. - +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | +| GetGameSessionPinConvergence | [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) | [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) | | +| GetGameInstanceRuntimeState | [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) | [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) | | +| ValidateBuiltInCommandAlias | [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) | [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) | | +| ListAdmissionPointers | [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) | [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) | | +| ListAdmissionPointerAudit | [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) | [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) | | +| GetGameplayCommandStatus | [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) | [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) | | +| GetRuntimeOwnershipStatus | [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) | [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) | | +| GetRemoteCommandCoordinator | [GetRemoteCommandCoordinatorRequest](#game_session-v1-GetRemoteCommandCoordinatorRequest) | [GetRemoteCommandCoordinatorResponse](#game_session-v1-GetRemoteCommandCoordinatorResponse) | | +| GetRemoteFollowup | [GetRemoteFollowupRequest](#game_session-v1-GetRemoteFollowupRequest) | [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) | | +| GetRemoteFollowupResult | [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) | [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) | | +| ListRemoteCommandCoordinators | [ListRemoteCommandCoordinatorsRequest](#game_session-v1-ListRemoteCommandCoordinatorsRequest) | [ListRemoteCommandCoordinatorsResponse](#game_session-v1-ListRemoteCommandCoordinatorsResponse) | | +| ScheduleRemoteFollowup | [ScheduleRemoteFollowupRequest](#game_session-v1-ScheduleRemoteFollowupRequest) | [ScheduleRemoteFollowupResponse](#game_session-v1-ScheduleRemoteFollowupResponse) | | +| ListRemoteFollowups | [ListRemoteFollowupsRequest](#game_session-v1-ListRemoteFollowupsRequest) | [ListRemoteFollowupsResponse](#game_session-v1-ListRemoteFollowupsResponse) | | +| ListRemoteFollowupResults | [ListRemoteFollowupResultsRequest](#game_session-v1-ListRemoteFollowupResultsRequest) | [ListRemoteFollowupResultsResponse](#game_session-v1-ListRemoteFollowupResultsResponse) | | +| SetAdmissionPointer | [SetAdmissionPointerRequest](#game_session-v1-SetAdmissionPointerRequest) | [SetAdmissionPointerResponse](#game_session-v1-SetAdmissionPointerResponse) | | +| ExecutePreparedVersionCutover | [ExecutePreparedVersionCutoverRequest](#game_session-v1-ExecutePreparedVersionCutoverRequest) | [ExecutePreparedVersionCutoverResponse](#game_session-v1-ExecutePreparedVersionCutoverResponse) | | +| SetPinnedScriptPatchVersion | [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) | [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) | | +| RollbackScriptPatchVersion | [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) | [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) | | +| PauseTicksForScope | [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) | [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) | | +| ResumeTicksForScope | [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) | [ResumeTicksForScopeResponse](#game_session-v1-ResumeTicksForScopeResponse) | | +| ValidateInstanceCutoverCompatibility | [ValidateInstanceCutoverCompatibilityRequest](#game_session-v1-ValidateInstanceCutoverCompatibilityRequest) | [ValidateInstanceCutoverCompatibilityResponse](#game_session-v1-ValidateInstanceCutoverCompatibilityResponse) | | +| PrepareVersionUpgrade | [PrepareVersionUpgradeRequest](#game_session-v1-PrepareVersionUpgradeRequest) | [PrepareVersionUpgradeResponse](#game_session-v1-PrepareVersionUpgradeResponse) | | +| GetPreparedVersionUpgrade | [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) | [GetPreparedVersionUpgradeResponse](#game_session-v1-GetPreparedVersionUpgradeResponse) | | +| EnqueueAutomationCommandIfAbsent | [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) | [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) | | +| PurgeQueuedTickCommandsForScriptPatch | [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) | [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) | | +| PurgeQueuedTickCommandsForPluginVersion | [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) | [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) | | - + -### EntityManagementService +### GameSessionService | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#entity_management-v1-PingRequest) | [PingResponse](#entity_management-v1-PingResponse) | | -| CreateCharacter | [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) | [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) | | -| UpdateEntity | [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) | [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) | | -| QueryInventory | [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | -| ListCharactersByAccount | [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) | [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) | | -| ListRoomEntities | [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) | [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) | | -| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) | | +| Ping | [PingRequest](#game_session-v1-PingRequest) | [PingResponse](#game_session-v1-PingResponse) | | +| StartSession | [StartSessionRequest](#game_session-v1-StartSessionRequest) | [StartSessionResponse](#game_session-v1-StartSessionResponse) | | +| StopSession | [StopSessionRequest](#game_session-v1-StopSessionRequest) | [StopSessionResponse](#game_session-v1-StopSessionResponse) | | +| RestartSession | [RestartSessionRequest](#game_session-v1-RestartSessionRequest) | [RestartSessionResponse](#game_session-v1-RestartSessionResponse) | | +| EnqueueCommand | [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) | [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) | | +| QueryState | [QueryStateRequest](#game_session-v1-QueryStateRequest) | [QueryStateResponse](#game_session-v1-QueryStateResponse) | | +| QueryAccountPresence | [QueryAccountPresenceRequest](#game_session-v1-QueryAccountPresenceRequest) | [QueryAccountPresenceResponse](#game_session-v1-QueryAccountPresenceResponse) | | +| ListGameplayWorlds | [ListGameplayWorldsRequest](#game_session-v1-ListGameplayWorldsRequest) | [ListGameplayWorldsResponse](#game_session-v1-ListGameplayWorldsResponse) | | +| ListGameplayRealms | [ListGameplayRealmsRequest](#game_session-v1-ListGameplayRealmsRequest) | [ListGameplayRealmsResponse](#game_session-v1-ListGameplayRealmsResponse) | | +| GetAdmissionPointer | [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) | [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) | | +| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) | | +| PauseTicks | [PauseTicksRequest](#game_session-v1-PauseTicksRequest) | [PauseTicksResponse](#game_session-v1-PauseTicksResponse) | Pause tick execution for an authorized maintenance workflow. | +| ResumeTicks | [ResumeTicksRequest](#game_session-v1-ResumeTicksRequest) | [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) | Resume tick execution after the authorized maintenance workflow completes. | +| GetTickStatus | [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) | [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) | Report whether ticks are currently paused. | - - + +

Top

-## game-design/v1/game_design_service.proto +## logging-admin/v1/logging_admin_service.proto - + -### ListVersionsRequest +### ApplyModerationActionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| session_id | [string](#string) | | | +| action | [string](#string) | | | +| reason | [string](#string) | | | - + -### ListVersionsResponse +### ApplyModerationActionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| versions | [Version](#gamedesign-v1-Version) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2112,59 +10340,83 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + + +### CreateLogEventRequest -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| producer_service | [string](#string) | | | +| event_type | [string](#string) | | | +| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| schema_version | [int32](#int32) | | | +| payload | [bytes](#bytes) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | + - + -### PingResponse +### CreateLogEventResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| receipt_id | [string](#string) | | | +| log_event_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | +| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | +| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | - + -### PublishScriptPatchVersionRequest +### EvaluateModerationPolicyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| base_version_id | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| notes | [string](#string) | | | +| account_id | [string](#string) | | | +| scope | [string](#string) | | | - + -### PublishScriptPatchVersionResponse +### EvaluateModerationPolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_id | [int64](#int64) | | | +| allowed | [bool](#bool) | | | +| action | [string](#string) | | | +| reason | [string](#string) | | | +| expires_at_epoch_seconds | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2172,31 +10424,25 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - - -### PublishVersionRequest - + +### PingRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| notes | [string](#string) | | | - + -### PublishVersionResponse +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_id | [int64](#int64) | | | +| message | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2204,32 +10450,31 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### SaveRevisionRequest +### QueryLogsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| data | [string](#string) | | | | tenant_id | [string](#string) | | | -| author_account_id | [int64](#int64) | | | +| filter | [string](#string) | | | - + -### SaveRevisionResponse +### QueryLogsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| revision_id | [int64](#int64) | | | +| entries | [string](#string) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2237,87 +10482,80 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### Version +### ReadLogEventReceiptRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| id | [int64](#int64) | | | -| version_number | [int32](#int32) | | | -| script_patch_version | [string](#string) | | | -| is_script_only | [bool](#bool) | | | -| notes | [string](#string) | | | - - - - +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| producer_service | [string](#string) | | | +| event_type | [string](#string) | | | +| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| schema_version | [int32](#int32) | | | +| payload | [bytes](#bytes) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | - - - - -### GameDesignService + +### ReadLogEventReceiptResponse -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#gamedesign-v1-PingRequest) | [PingResponse](#gamedesign-v1-PingResponse) | | -| SaveRevision | [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) | [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) | | -| PublishVersion | [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) | [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) | | -| PublishScriptPatchVersion | [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) | [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) | | -| ListVersions | [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) | [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) | | - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| receipt_id | [string](#string) | | | +| log_event_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | +| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | +| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | - -

Top

-## game-logic/v1/game_logic_service.proto - + -### BroadcastSayRequest +### ToggleFeatureFlagRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| alias | [ChatAlias](#game_logic-v1-ChatAlias) | | | -| text | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| name | [string](#string) | | | +| enabled | [bool](#bool) | | | - + -### BroadcastSayResponse +### ToggleFeatureFlagResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | success | [bool](#bool) | | | -| message | [string](#string) | | | -| delivered_to | [string](#string) | repeated | | -| npc_echoes | [string](#string) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2325,338 +10563,304 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - - -### DoorAmbientState - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| door_id | [string](#string) | | | -| state | [DoorState](#game_logic-v1-DoorState) | | | + +### AccountAuditReceiptOutcome +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED | 1 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE | 2 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE | 3 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT | 4 | | - -### ExecuteCommandRequest + +### AccountAuditReceiptStatus -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| command | [string](#string) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED | 1 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED | 2 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT | 3 | | + +### AccountAuditScope - -### ExecuteCommandResponse +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_AUDIT_SCOPE_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_SCOPE_PLATFORM | 1 | | +| ACCOUNT_AUDIT_SCOPE_TENANT | 2 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| result | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### LoggingAdminService - -### HazardAmbientState +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#logging_admin-v1-PingRequest) | [PingResponse](#logging_admin-v1-PingResponse) | | +| QueryLogs | [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) | [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) | | +| CreateLogEvent | [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) | [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) | | +| ReadLogEventReceipt | [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) | [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) | | +| ApplyModerationAction | [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) | [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) | | +| EvaluateModerationPolicy | [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) | [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) | | +| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| hazard_id | [string](#string) | | | -| state | [HazardState](#game_logic-v1-HazardState) | | | + +

Top

+## logging-admin/v1/report_service.proto - + -### LookExit +### CreateReportRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| label | [string](#string) | | | +| tenant_id | [string](#string) | | | +| reporter_account_id | [string](#string) | | | +| target_account_id | [string](#string) | | | +| type | [string](#string) | | | | description | [string](#string) | | | -| target_room_instance_id | [string](#string) | | | - + -### LookRequest +### CreateReportResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| report_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### LookResult -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| room_name | [string](#string) | | | -| short_description | [string](#string) | | | -| long_description | [string](#string) | | | -| exits | [LookExit](#game_logic-v1-LookExit) | repeated | | -| entities | [RoomEntity](#game_logic-v1-RoomEntity) | repeated | | -| room_flags | [string](#string) | repeated | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| world_snapshot_id | [string](#string) | | | -| entity_snapshot_id | [string](#string) | | | -| look_snapshot_id | [string](#string) | | | -| ambient_state | [RoomAmbientState](#game_logic-v1-RoomAmbientState) | | | + +### ReportService +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| CreateReport | [CreateReportRequest](#logging_admin-v1-CreateReportRequest) | [CreateReportResponse](#logging_admin-v1-CreateReportResponse) | | - -### PingRequest + +

Top

+## shared/v1/errors.proto - + -### PingResponse +### ErrorDetail | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| code | [string](#string) | | | | message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### RoomAmbientState -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | | | -| doors | [DoorAmbientState](#game_logic-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#game_logic-v1-HazardAmbientState) | repeated | | + +

Top

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

Top

- +## shared/v1/paging.proto -### EntityType -| Name | Number | Description | -| ---- | ------ | ----------- | -| ENTITY_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | -| ITEM | 3 | | + +### PagingRequest +Standard paging request for list RPCs. - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| page | [int32](#int32) | | 1-based page index. | +| page_size | [int32](#int32) | | Maximum number of items per page. | -### HazardState -| Name | Number | Description | -| ---- | ------ | ----------- | -| HAZARD_STATE_UNSPECIFIED | 0 | | -| ACTIVE | 1 | | -| INACTIVE | 2 | | - - - -### GameLogicService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#game_logic-v1-PingRequest) | [PingResponse](#game_logic-v1-PingResponse) | | -| ExecuteCommand | [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) | [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) | | -| ResolveLook | [LookRequest](#game_logic-v1-LookRequest) | [LookResult](#game_logic-v1-LookResult) | | -| BroadcastSay | [BroadcastSayRequest](#game_logic-v1-BroadcastSayRequest) | [BroadcastSayResponse](#game_logic-v1-BroadcastSayResponse) | | - - +

Top

-## game-session/v1/game_session_service.proto - +## shared/v1/player_execution_context.proto - -### EnqueueCommandRequest + +### PlayerExecutionContext +Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. +Receivers validate the required subset and equality with their own authoritative target. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | | session_id | [string](#string) | | | -| command | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | +| realm_id | [string](#string) | | | +| request_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | - -### EnqueueCommandResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| accepted | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

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

Top

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

Top

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

Top

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

Top

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

Top

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

Top

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

Top

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

Top

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

Top

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

Top

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

Top

-## world-management/v1/world_management_service.proto +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| name | [string](#string) | | | +| weather | [string](#string) | | | +| shard_id | [int32](#int32) | | | +| generation_seed | [int64](#int64) | | | +| generator_type | [string](#string) | | | +| generator_params | [string](#string) | | | +| spacing_multiplier | [double](#double) | | | - -### ApplyRoomAmbientStatePatchRequest + + + + +### RoomAmbientState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| effect_id | [string](#string) | | | -| ambient_state_patch | [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) | | | +| schema_version | [int32](#int32) | | | +| weather | [string](#string) | | | +| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | +| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | - + -### ApplyRoomAmbientStatePatchResponse +### RoomAmbientStatePatch | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| success | [bool](#bool) | | | -| world_snapshot_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | +| weather | [string](#string) | optional | | +| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | +| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | - + -### DoorAmbientState +### RoomDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| door_id | [string](#string) | | | -| state | [DoorState](#world_management-v1-DoorState) | | | +| name | [string](#string) | | | +| description | [string](#string) | | | +| zone_id | [string](#string) | | | +| name_localized_variants_json | [string](#string) | | | +| description_localized_variants_json | [string](#string) | | | - + -### GetDraftDesignDigestRequest +### RoomExitDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | +| from_room_id | [string](#string) | | | +| to_room_id | [string](#string) | | | +| direction | [string](#string) | | | +| cost | [int32](#int32) | | | - + -### GetDraftDesignDigestResponse +### RoomExitSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| exit_id | [string](#string) | | | +| target_room_name | [string](#string) | | | +| direction | [string](#string) | | | +| label | [string](#string) | | | +| description | [string](#string) | | | +| cost | [int32](#int32) | | | +| target_room_instance_id | [string](#string) | | | - + -### GetRoomRequest +### RoomOccupant | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| entity_id | [string](#string) | | | +| occupant_type | [RoomOccupantType](#world_management-v1-RoomOccupantType) | | | - + -### GetRoomResponse +### RoomSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room | [RuntimeRoom](#world_management-v1-RuntimeRoom) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| room_name | [string](#string) | | | +| short_description | [string](#string) | | | +| long_description | [string](#string) | | | +| exits | [RoomExitSnapshot](#world_management-v1-RoomExitSnapshot) | repeated | | +| room_flags | [string](#string) | repeated | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| world_snapshot_id | [string](#string) | | | +| ambient_state | [RoomAmbientState](#world_management-v1-RoomAmbientState) | | | @@ -4110,31 +12405,35 @@ Semantics and failure expectations: - Events may be delivered more than once; th - -### GetRoomSnapshotRequest + + +### TerminateWorldInstanceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| game_instance_id | [string](#string) | | | +| expected_lifecycle_epoch | [int64](#int64) | | | +| termination_request_id | [string](#string) | | | +| reason | [string](#string) | | | - + -### GetRoomSnapshotResponse +### TerminateWorldInstanceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| snapshot | [RoomSnapshot](#world_management-v1-RoomSnapshot) | | | +| world_instance | [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -4142,221 +12441,289 @@ Semantics and failure expectations: - Events may be delivered more than once; th - + -### HazardAmbientState +### ValidateWorldUpgradeMappingsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| hazard_id | [string](#string) | | | -| state | [HazardState](#world_management-v1-HazardState) | | | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | - + -### ListRoomOccupantsRequest +### ValidateWorldUpgradeMappingsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [UpgradeValidationResult](#world_management-v1-UpgradeValidationResult) | | | +| remap_set_required | [bool](#bool) | | | +| reasons | [string](#string) | repeated | | +| remap_set_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ListRoomOccupantsResponse +### WorldEntitySpawnBindingDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| occupant_snapshot_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| occupants | [RoomOccupant](#world_management-v1-RoomOccupant) | repeated | | +| room_id | [string](#string) | | | +| entity_template_type | [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) | | | +| entity_template_id | [string](#string) | | | +| spawn_count | [int32](#int32) | | | +| respawn_delay_seconds | [int32](#int32) | | | - + + +### WorldGenerationSubtreeDesignMutation + -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| generation_rules | [GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) | repeated | | +| rooms | [GeneratedRoomDesignMutation](#world_management-v1-GeneratedRoomDesignMutation) | repeated | | +| room_exits | [GeneratedRoomExitDesignMutation](#world_management-v1-GeneratedRoomExitDesignMutation) | repeated | | +| world_entity_spawn_bindings | [GeneratedWorldEntitySpawnBindingDesignMutation](#world_management-v1-GeneratedWorldEntitySpawnBindingDesignMutation) | repeated | | - + -### PingResponse +### WorldInstanceLifecycleSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| game_template_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| version_id | [string](#string) | | | +| release_bundle_id | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| published_release_bundle_ref | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| lifecycle_epoch | [int64](#int64) | | | +| status | [WorldInstanceLifecycleStatus](#world_management-v1-WorldInstanceLifecycleStatus) | | | +| remap_set_id | [string](#string) | | | +| workflow_id | [string](#string) | | | +| workflow_run_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| workflow_family | [string](#string) | | | - + -### RoomAmbientState +### ZoneDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | | | -| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | +| name | [string](#string) | | | +| region_id | [string](#string) | | | - -### RoomAmbientStatePatch + +### DoorState -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | optional | | -| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| DOOR_STATE_UNSPECIFIED | 0 | | +| OPEN | 1 | | +| CLOSED | 2 | | +| LOCKED | 3 | | + +### EntityTemplateReferenceType - -### RoomExitSnapshot +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED | 0 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM | 1 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_NPC | 2 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| exit_id | [string](#string) | | | -| target_room_name | [string](#string) | | | -| label | [string](#string) | | | -| description | [string](#string) | | | -| cost | [int32](#int32) | | | -| target_room_instance_id | [string](#string) | | | + + +### HazardState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| HAZARD_STATE_UNSPECIFIED | 0 | | +| ACTIVE | 1 | | +| INACTIVE | 2 | | + +### RoomOccupantType - +| Name | Number | Description | +| ---- | ------ | ----------- | +| ROOM_OCCUPANT_TYPE_UNSPECIFIED | 0 | | +| PLAYER | 1 | | +| NPC | 2 | | -### RoomOccupant + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| occupant_type | [RoomOccupantType](#world_management-v1-RoomOccupantType) | | | +### UpgradeValidationResult +| Name | Number | Description | +| ---- | ------ | ----------- | +| UPGRADE_VALIDATION_RESULT_UNSPECIFIED | 0 | | +| UPGRADE_VALIDATION_RESULT_COMPATIBLE | 1 | | +| UPGRADE_VALIDATION_RESULT_REQUIRES_MAPPING | 2 | | +| UPGRADE_VALIDATION_RESULT_INCOMPATIBLE | 3 | | +| UPGRADE_VALIDATION_RESULT_UNAVAILABLE | 4 | | + - +### WorldDesignAggregateType -### RoomSnapshot +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_DESIGN_AGGREGATE_TYPE_UNSPECIFIED | 0 | | +| WORLD_DESIGN_AGGREGATE_TYPE_REGION | 1 | | +| WORLD_DESIGN_AGGREGATE_TYPE_ZONE | 2 | | +| WORLD_DESIGN_AGGREGATE_TYPE_ROOM | 3 | | +| WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT | 4 | | +| WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE | 5 | | +| WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING | 6 | | +| WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE | 7 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| room_name | [string](#string) | | | -| short_description | [string](#string) | | | -| long_description | [string](#string) | | | -| exits | [RoomExitSnapshot](#world_management-v1-RoomExitSnapshot) | repeated | | -| room_flags | [string](#string) | repeated | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| world_snapshot_id | [string](#string) | | | -| ambient_state | [RoomAmbientState](#world_management-v1-RoomAmbientState) | | | + +### WorldDesignMutationOperation +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_DESIGN_MUTATION_OPERATION_UNSPECIFIED | 0 | | +| WORLD_DESIGN_MUTATION_OPERATION_UPSERT | 1 | | +| WORLD_DESIGN_MUTATION_OPERATION_DELETE | 2 | | - - + -### DoorState +### WorldDesignMutationResult | Name | Number | Description | | ---- | ------ | ----------- | -| DOOR_STATE_UNSPECIFIED | 0 | | -| OPEN | 1 | | -| CLOSED | 2 | | -| LOCKED | 3 | | +| WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED | 0 | | +| WORLD_DESIGN_MUTATION_RESULT_APPLIED | 1 | | +| WORLD_DESIGN_MUTATION_RESULT_NO_OP_ALREADY_APPLIED | 2 | | - + -### HazardState +### WorldDesignScopeMutationPolicy | Name | Number | Description | | ---- | ------ | ----------- | -| HAZARD_STATE_UNSPECIFIED | 0 | | -| ACTIVE | 1 | | -| INACTIVE | 2 | | +| WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED | 0 | | +| WORLD_DESIGN_SCOPE_MUTATION_POLICY_REPLACE_SCOPE | 1 | | +| WORLD_DESIGN_SCOPE_MUTATION_POLICY_SEED_APPEND_ONLY | 2 | | - + -### RoomOccupantType +### WorldDesignScopeType | Name | Number | Description | | ---- | ------ | ----------- | -| ROOM_OCCUPANT_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | +| WORLD_DESIGN_SCOPE_TYPE_UNSPECIFIED | 0 | | +| WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE | 1 | | +| WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE | 2 | | +| WORLD_DESIGN_SCOPE_TYPE_NEW_EMPTY_REGION | 3 | | + + + + + +### WorldInstanceLifecycleStatus + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED | 0 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING | 1 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE | 2 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION | 3 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING | 4 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED | 5 | | + + - - @@ -4367,13 +12734,20 @@ Semantics and failure expectations: - Events may be delivered more than once; th | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| | Ping | [PingRequest](#world_management-v1-PingRequest) | [PingResponse](#world_management-v1-PingResponse) | | +| PrepareWorldInstance | [PrepareWorldInstanceRequest](#world_management-v1-PrepareWorldInstanceRequest) | [PrepareWorldInstanceResponse](#world_management-v1-PrepareWorldInstanceResponse) | | +| ActivatePreparedWorldInstance | [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) | [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) | | +| FailPreparedWorldInstance | [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) | [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) | | +| GetWorldInstanceLifecycle | [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) | [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) | | +| TerminateWorldInstance | [TerminateWorldInstanceRequest](#world_management-v1-TerminateWorldInstanceRequest) | [TerminateWorldInstanceResponse](#world_management-v1-TerminateWorldInstanceResponse) | | | GetRoom | [GetRoomRequest](#world_management-v1-GetRoomRequest) | [GetRoomResponse](#world_management-v1-GetRoomResponse) | | | GetRoomSnapshot | [GetRoomSnapshotRequest](#world_management-v1-GetRoomSnapshotRequest) | [GetRoomSnapshotResponse](#world_management-v1-GetRoomSnapshotResponse) | | | GetDraftDesignDigest | [GetDraftDesignDigestRequest](#world_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#world_management-v1-GetDraftDesignDigestResponse) | | +| ApplyWorldDesignMutation | [ApplyWorldDesignMutationRequest](#world_management-v1-ApplyWorldDesignMutationRequest) | [ApplyWorldDesignMutationResponse](#world_management-v1-ApplyWorldDesignMutationResponse) | | +| ValidateWorldUpgradeMappings | [ValidateWorldUpgradeMappingsRequest](#world_management-v1-ValidateWorldUpgradeMappingsRequest) | [ValidateWorldUpgradeMappingsResponse](#world_management-v1-ValidateWorldUpgradeMappingsResponse) | | | ListRoomOccupants | [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) | [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) | | | ApplyRoomAmbientStatePatch | [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) | [ApplyRoomAmbientStatePatchResponse](#world_management-v1-ApplyRoomAmbientStatePatchResponse) | | - + diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 297e08f1b8..135d284088 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,18 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The current [#2933](https://github.com/benhook1013/FireMUD/pull/2933) candidate adds exact historical issuer-event/current-checkpoint readback and the dedicated, closed issuer-source RPC contract at [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). Its Account handler requires the exact Game Session workload peer; its Game Session client requires the exact Account server peer and validates complete current/selected historical source evidence with arbitrary-precision counters. Both remain unwired. Nine producer unit, ten handler unit, fifteen client unit and six real-socket mTLS cases executed cleanly locally. The physical tests cover successful current/historical reads, trusted wrong-service/wrong-namespace callers and servers, and missing-client-certificate handshake rejection. They mock the owner-local producer, so they do not prove a combined PostgreSQL/transport transaction, delivered revocation, projection installation or live credentials. All fifteen issuer PostgreSQL cases compiled but skipped locally without Docker; the preceding exact-head runner proved twelve before the three historical-read cases were added. The existing CI strict proof mechanism now requires those additional cases and retains the six socket-case XML results before broader transport checks. + +The corrected combined Common Security/Game Logic/Account/Common Platform/Game Session/TCP checks and three affected boot JARs, links and Markdown passed 256 tasks (88 executed, 168 up-to-date), including formatting, Checkstyle, SpotBugs and JaCoCo. Common Security executed 120 unit cases, including all 28 gameplay-attestation cases; Game Logic executed 91 unit and five integration cases; Account executed 545 unit cases with all 182 PostgreSQL cases skipped; Game Session executed 1,828 unit, eighteen integration and seven cross-service cases, with 17/143/33 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. Common Platform's 139 unit results were reused from the preceding same-code gate. Executed cases were clean. The new exact-head runner still must execute historical database and composed transport proof. Fresh-image and live activation proof remain open; the protobuf generator succeeded, while local `buf lint` is unavailable because `buf` is not installed. + +Exact preceding-head [CI 36955774965](https://github.com/benhook1013/FireMUD/actions/runs/36955774965) at `8344e6ea134ccbe52a90e4c554b2fee770ad53a7` executed twelve issuer, seventeen retained-association, six reset-producer and nine reset-application PostgreSQL cases without skips/failures/errors, including the pointer regression and both required reset application assertions. Aggregate CI failed: broader TCP reported twelve of seventeen failures with `SESSION_ATTESTATION_INVALID Malformed claim: accountId`; Game Session exceeded twenty minutes after communication setup failures and supplied no broad report, so its detailed cause is not established. The TCP failure was a stale shared validator parsing the current Account UUID as a number. The correction preserves the exact canonical non-nil Account UUID, rejects malformed/numeric/nil/noncanonical identities, and leaves the separate legacy numeric runtime tenant/session/character/instance/pointer and internal-probe semantics intact. This is not a tenant migration or typed workload-context completion. Positive broad runner execution is still required. + +Issuer projection/bootstrap/contiguous advancement/immutable duplicate verification, delivery and active-binding revocation remain required implementations. The accepted source-only projection contract does not require a recipient tuple/fence; admission and rebind still do. Missing role-bound Redis registration is a named infrastructure prerequisite, not proof supplied by a local script. Membership RPC, credential/context/catalog activation and the Account ring mount remain denied. Unit 1B is provisional. + +### Earlier checkpoint evidence + +The following checkpoints retain their original scopes and execution limits; they do not override the current state above. + The issuer-generation source batch in [#2933](https://github.com/benhook1013/FireMUD/pull/2933) declares the closed `account-auth-issuer-generation-event/v1` schema at Authentication, with a shared strict codec and fixed/large-counter vectors. An unwired Account producer owns a short row-fenced transaction that advances the exact persisted issuer generation/source version and appends its immutable event/checkpoint together, then requires exact post-commit readback. Same-request recovery returns its original event after later advances; changed expected state, wrong issuer, absent source, contradictory checkpoint and counter overflow deny without enrollment or a second mutation. Seven unit and twelve PostgreSQL cases cover input/snapshot shape, concurrent retry, rollback and committed-but-unacknowledged recovery. The corrected combined Account/Common Platform/Game Session/TCP check passed 213 tasks, 68 executed and 145 up-to-date, including formatting, Checkstyle, SpotBugs and JaCoCo. Account executed 533 unit cases, including all seven producer cases; Common Platform's earlier same-code check executed 139 cases, including six new codec cases, with results reused by the combined gate. All 179 Account PostgreSQL cases compiled but skipped without Docker, including the twelve issuer cases. Game Session executed 1,813 unit, eighteen integration and one cross-service case, with 17/143/33 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen cross-service skips. All executed cases were clean. All seventeen association PostgreSQL cases, including the new pointer regression, compiled but skipped locally. Exact-head runner execution and full transport proof remain required. The local component is not an authenticated source handoff, signing-key rotation, delivered revocation or Game Session issuer projection; those implementations and their executed proof remain required. No recipient Account tuple/fence is fabricated for issuer-scoped source maintenance. Runtime activation and the ring mount remain denied. Exact preceding-head [CI 36952328785](https://github.com/benhook1013/FireMUD/actions/runs/36952328785) at `c5bebbf4d97cc08cefa0986faa69948102a75b45` executed all sixteen association and eight required password-reset PostgreSQL methods with no skips, failures or errors; the complete intended XML artifacts were retrieved and parsed. Its broader Game Session and Account-backed TCP setup failures share a concrete fixture cause: the baseline truncated runtime instances while retaining canonical demo/sandbox pointers, so the strict snapshot validator correctly rejected the dangling sandbox target before gameplay assertions. The corrected synthetic baseline preserves those pointers and reuses explicitly declared instances 1/2, rejecting tenant/owner identity conflicts and never reducing the generated-ID sequence. A new PostgreSQL case checks repeated baselines, pointer targets and unchanged immutable association receipts. This test-only correction does not guess a retained production association or weaken the snapshot guard; corrected-head database and broad transport execution remain separate proof gates. diff --git a/protos/account/v1/issuer_authority_service.proto b/protos/account/v1/issuer_authority_service.proto new file mode 100644 index 0000000000..b067b0f7cf --- /dev/null +++ b/protos/account/v1/issuer_authority_service.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Owner-local source evidence only; this service is not wired for runtime use. +// Caller and response workload identities must both be verified from mTLS. +service IssuerAuthorityService { + rpc ReadIssuerAuthorityForRuntime(ReadIssuerAuthorityForRuntimeRequest) + returns (ReadIssuerAuthorityForRuntimeResponse); +} + +message ReadIssuerAuthorityForRuntimeRequest { + string issuer_id = 1; + string request_id = 2; + // Omit for current source evidence; when present, must be canonical positive. + optional string requested_outbox_sequence = 3; +} + +message IssuerAuthoritySourceSnapshot { + string issuer_id = 1; + string source_scope = 2; + string outbox_stream_key = 3; + string issuer_auth_generation = 4; + string source_version = 5; + string outbox_sequence = 6; + // Must be absent at sequence zero, present and exact at positive sequence. + optional string latest_event_canonical_json = 7; +} + +message ReadIssuerAuthorityForRuntimeResponse { + string schema_version = 1; + string target_namespace = 2; + string request_id = 3; + IssuerAuthoritySourceSnapshot source_snapshot = 4; + // Present exactly when the request selected a positive historical sequence. + optional string requested_event_canonical_json = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java index 961e7b6254..1685b850f9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Map; @@ -126,6 +127,30 @@ public IssuerAuthoritySnapshot readCurrent(String requestedIssuerId) { return snapshot; } + /** + * Reads one exact retained immutable event together with the current source and checkpoint + * evidence that bounds it, all while holding the issuer source row lock. + * + *

The historical event is returned only as historical evidence. Callers must use {@link + * IssuerAuthorityEventReadback#currentSnapshot()} for current source decisions. + */ + public IssuerAuthorityEventReadback readCommittedEvent( + String requestedIssuerId, long outboxSequence) { + requireExactIssuer(requestedIssuerId); + if (outboxSequence <= 0L) { + throw new IllegalArgumentException("Issuer outbox sequence must be positive"); + } + requireNoAmbientTransaction(); + + IssuerAuthorityEventReadback readback = + ownerTransaction.execute(status -> readCommittedEventInTransaction(outboxSequence)); + if (readback == null) { + throw new IllegalStateException( + "Issuer authority event readback transaction returned no state"); + } + return readback; + } + private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( UUID requestId, long expectedGeneration, long expectedSourceVersion) { ScopeState current = readLockedIssuerState(); @@ -251,6 +276,41 @@ private IssuerAuthoritySnapshot readCurrentInTransaction() { history.event()); } + private IssuerAuthorityEventReadback readCommittedEventInTransaction(long outboxSequence) { + ScopeState current = readLockedIssuerState(); + LatestEvidence currentHistory = requireCurrentHistoryMatches(current); + if (outboxSequence > currentHistory.sequence()) { + throw new IllegalStateException("Requested issuer event is ahead of the current checkpoint"); + } + Event requested = + outboxRepository + .findEvent(outboxStreamKey, outboxSequence) + .orElseThrow( + () -> new IllegalStateException("Requested retained issuer event is missing")); + IssuerGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(requested); + requireHistoricalEventIsRetained(requested, current, currentHistory); + if (requested.outboxSequence() != outboxSequence) { + throw new IllegalStateException( + "Requested issuer event sequence differs from its lookup key"); + } + + IssuerAuthoritySnapshot currentSnapshot = + new IssuerAuthoritySnapshot( + exactIssuerId, + current.generation(), + current.sourceVersion(), + outboxStreamKey, + currentHistory.sequence(), + currentHistory.event()); + if (outboxSequence == currentHistory.sequence() + && (currentHistory.event().isEmpty() + || !sameEvent(verified, currentHistory.event().orElseThrow()))) { + throw new IllegalStateException( + "Requested latest issuer event differs from current source checkpoint evidence"); + } + return new IssuerAuthorityEventReadback(currentSnapshot, verified); + } + private ScopeState readLockedIssuerState() { ScopeState state = generationRepository.read(issuerScope); if (state == null @@ -464,8 +524,7 @@ private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { private void requireExactIssuer(String requestedIssuerId) { if (!exactIssuerId.equals(requestedIssuerId)) { - throw new IllegalArgumentException( - "Issuer authority request must name the exact configured issuer"); + throw new IssuerMismatchException(); } } @@ -507,6 +566,15 @@ private static boolean sameEvent( && MessageDigest.isEqual(first.canonicalJsonUtf8(), second.canonicalJsonUtf8()); } + /** A caller selected an issuer other than this producer's configured authority. */ + public static final class IssuerMismatchException extends IllegalArgumentException { + private static final long serialVersionUID = 1L; + + public IssuerMismatchException() { + super("Issuer authority request must name the exact configured issuer"); + } + } + /** Current exact source evidence; the event is omitted when the proven checkpoint is zero. */ public record IssuerAuthoritySnapshot( String issuerId, @@ -553,6 +621,58 @@ public record IssuerAuthoritySnapshot( } } + /** + * Exact retained event evidence tied to the current issuer source/checkpoint snapshot. + * + *

This shape proves only owner-local source evidence; it does not establish source + * authentication, transport authenticity, consumer provenance, or issuer authorization. + */ + public record IssuerAuthorityEventReadback( + IssuerAuthoritySnapshot currentSnapshot, IssuerGenerationAuthorityEvent requestedEvent) { + public IssuerAuthorityEventReadback { + currentSnapshot = + Objects.requireNonNull(currentSnapshot, "current issuer authority snapshot is required"); + requestedEvent = + Objects.requireNonNull(requestedEvent, "requested issuer authority event is required"); + if (currentSnapshot.outboxSequence() <= 0L + || !currentSnapshot.issuerId().equals(requestedEvent.issuerId()) + || !("issuer/" + currentSnapshot.issuerId()).equals(requestedEvent.sourceScope()) + || !currentSnapshot.outboxStreamKey().equals(requestedEvent.outboxStreamKey())) { + throw new IllegalArgumentException( + "Requested issuer event does not bind a positive current issuer snapshot"); + } + + BigInteger requestedSequence = parsePositiveCounter(requestedEvent.outboxSequence()); + BigInteger currentSequence = BigInteger.valueOf(currentSnapshot.outboxSequence()); + BigInteger requestedGeneration = parsePositiveCounter(requestedEvent.issuerAuthGeneration()); + BigInteger requestedSourceVersion = parsePositiveCounter(requestedEvent.sourceVersion()); + if (requestedSequence.compareTo(currentSequence) > 0 + || requestedGeneration.compareTo( + BigInteger.valueOf(currentSnapshot.issuerAuthGeneration())) + > 0 + || requestedSourceVersion.compareTo(BigInteger.valueOf(currentSnapshot.sourceVersion())) + > 0) { + throw new IllegalArgumentException( + "Requested historical issuer event is ahead of the current snapshot"); + } + + if (requestedSequence.equals(currentSequence) + && (currentSnapshot.latestEvent().isEmpty() + || !sameEvent(requestedEvent, currentSnapshot.latestEvent().orElseThrow()))) { + throw new IllegalArgumentException( + "Requested latest issuer event differs from the current snapshot checkpoint"); + } + } + + private static BigInteger parsePositiveCounter(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Issuer event counters must be canonical positive integers"); + } + return new BigInteger(value); + } + } + private record LatestEvidence( long sequence, Optional event, Optional outboxEvent) { private LatestEvidence { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java new file mode 100644 index 0000000000..aacbd66f86 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.accountservice.service; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.sql.SQLTransientException; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.dao.TransientDataAccessException; + +/** + * Unwired transport candidate for Account-owned issuer source readback. + * + *

This implementation exposes no runtime bean. Its only successful response is derived from a + * complete local producer readback and an exact certificate-derived Game Session peer identity. + */ +public final class AccountIssuerAuthorityGrpcService + extends IssuerAuthorityServiceGrpc.IssuerAuthorityServiceImplBase { + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final String SOURCE_SCOPE_PREFIX = "issuer/"; + private static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + private static final String READBACK_SCHEMA_VERSION = "account-auth-issuer-source-readback/v1"; + + private final AccountIssuerAuthorityEventProducer producer; + + private final String workloadNamespace; + private final String expectedGameSessionPeerUri; + + public AccountIssuerAuthorityGrpcService( + AccountIssuerAuthorityEventProducer producer, String workloadNamespace) { + this.producer = Objects.requireNonNull(producer, "issuer authority producer is required"); + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + GrpcPeerIdentity expectedPeer = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + GAME_SESSION_SERVICE) + .filter(identity -> workloadNamespace.equals(identity.namespace())) + .filter(identity -> identity.isService(GAME_SESSION_SERVICE)) + .orElseThrow( + () -> new IllegalArgumentException("Account workload namespace is invalid")); + this.workloadNamespace = expectedPeer.namespace(); + this.expectedGameSessionPeerUri = expectedPeer.uri(); + } + + @Override + public void readIssuerAuthorityForRuntime( + ReadIssuerAuthorityForRuntimeRequest request, + StreamObserver responseObserver) { + if (!hasExactGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + + final RequestSelection selection; + try { + selection = validateRequest(request); + } catch (InvalidRequestException invalidRequest) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Issuer authority read request is invalid") + .asRuntimeException()); + return; + } + + final ReadIssuerAuthorityForRuntimeResponse response; + try { + response = readAndEncode(selection); + } catch (RuntimeException sourceFailure) { + Status.Code code = + isExactIssuerMismatch(sourceFailure) + ? Status.Code.INVALID_ARGUMENT + : sourceFailureCode(sourceFailure); + String description = + code == Status.Code.UNAVAILABLE + ? "Issuer authority source is temporarily unavailable" + : isExactIssuerMismatch(sourceFailure) + ? "Issuer authority read request is invalid" + : "Issuer authority source evidence is unavailable or contradictory"; + responseObserver.onError( + Status.fromCode(code).withDescription(description).asRuntimeException()); + return; + } + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean hasExactGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null && expectedGameSessionPeerUri.equals(peer.uri()); + } + + private RequestSelection validateRequest(ReadIssuerAuthorityForRuntimeRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new InvalidRequestException(); + } + if (request.getIssuerId().isBlank()) { + throw new InvalidRequestException(); + } + + UUID requestId; + try { + requestId = UUID.fromString(request.getRequestId()); + } catch (IllegalArgumentException malformed) { + throw new InvalidRequestException(); + } + if (new UUID(0L, 0L).equals(requestId) + || !requestId.toString().equals(request.getRequestId())) { + throw new InvalidRequestException(); + } + + Optional requestedSequence = Optional.empty(); + if (request.hasRequestedOutboxSequence()) { + String sequenceText = request.getRequestedOutboxSequence(); + if (!sequenceText.matches("[1-9][0-9]*")) { + throw new InvalidRequestException(); + } + try { + requestedSequence = Optional.of(Long.parseLong(sequenceText)); + } catch (NumberFormatException outsideBigintRange) { + throw new InvalidRequestException(); + } + } + + return new RequestSelection(request.getIssuerId(), requestId.toString(), requestedSequence); + } + + private ReadIssuerAuthorityForRuntimeResponse readAndEncode(RequestSelection selection) { + IssuerAuthoritySnapshot currentSnapshot; + IssuerGenerationAuthorityEvent requestedEvent = null; + if (selection.requestedSequence().isPresent()) { + IssuerAuthorityEventReadback readback = + producer.readCommittedEvent( + selection.issuerId(), selection.requestedSequence().orElseThrow()); + if (readback == null) { + throw new IllegalStateException("Issuer authority historical readback is absent"); + } + currentSnapshot = readback.currentSnapshot(); + requestedEvent = readback.requestedEvent(); + } else { + currentSnapshot = producer.readCurrent(selection.issuerId()); + } + + validateCurrentSnapshot(currentSnapshot, selection.issuerId()); + if (selection.requestedSequence().isPresent()) { + validateHistoricalEvent( + requestedEvent, currentSnapshot, selection.requestedSequence().orElseThrow()); + } + + IssuerAuthoritySourceSnapshot.Builder snapshotResponse = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(currentSnapshot.issuerId()) + .setSourceScope(SOURCE_SCOPE_PREFIX + currentSnapshot.issuerId()) + .setOutboxStreamKey(currentSnapshot.outboxStreamKey()) + .setIssuerAuthGeneration(Long.toString(currentSnapshot.issuerAuthGeneration())) + .setSourceVersion(Long.toString(currentSnapshot.sourceVersion())) + .setOutboxSequence(Long.toString(currentSnapshot.outboxSequence())); + currentSnapshot + .latestEvent() + .ifPresent(event -> snapshotResponse.setLatestEventCanonicalJson(event.canonicalJson())); + + ReadIssuerAuthorityForRuntimeResponse.Builder response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion(READBACK_SCHEMA_VERSION) + .setTargetNamespace(workloadNamespace) + .setRequestId(selection.requestId()) + .setSourceSnapshot(snapshotResponse); + if (requestedEvent != null) { + response.setRequestedEventCanonicalJson(requestedEvent.canonicalJson()); + } + return response.build(); + } + + private static void validateCurrentSnapshot(IssuerAuthoritySnapshot snapshot, String issuerId) { + if (snapshot == null + || !issuerId.equals(snapshot.issuerId()) + || snapshot.issuerAuthGeneration() <= 0L + || snapshot.sourceVersion() <= 0L + || snapshot.outboxSequence() < 0L + || !(EVENT_STREAM_PREFIX + SOURCE_SCOPE_PREFIX + issuerId) + .equals(snapshot.outboxStreamKey())) { + throw new IllegalStateException( + "Issuer authority current snapshot is incomplete or mismatched"); + } + + Optional latestEvent = snapshot.latestEvent(); + if (latestEvent == null || (snapshot.outboxSequence() == 0L) != latestEvent.isEmpty()) { + throw new IllegalStateException("Issuer authority current checkpoint is incomplete"); + } + if (snapshot.outboxSequence() == 0L) { + if (snapshot.issuerAuthGeneration() != 1L || snapshot.sourceVersion() != 1L) { + throw new IllegalStateException("Issuer authority baseline is contradictory"); + } + return; + } + + IssuerGenerationAuthorityEvent latest = latestEvent.orElseThrow(); + verifyCompleteEvent(latest); + if (!issuerId.equals(latest.issuerId()) + || !(SOURCE_SCOPE_PREFIX + issuerId).equals(latest.sourceScope()) + || !snapshot.outboxStreamKey().equals(latest.outboxStreamKey()) + || !Long.toString(snapshot.outboxSequence()).equals(latest.outboxSequence()) + || !Long.toString(snapshot.issuerAuthGeneration()).equals(latest.issuerAuthGeneration()) + || !Long.toString(snapshot.sourceVersion()).equals(latest.sourceVersion())) { + throw new IllegalStateException("Issuer authority latest event differs from its checkpoint"); + } + } + + private static void validateHistoricalEvent( + IssuerGenerationAuthorityEvent event, + IssuerAuthoritySnapshot currentSnapshot, + long requestedSequence) { + verifyCompleteEvent(event); + String exactIssuer = currentSnapshot.issuerId(); + if (!exactIssuer.equals(event.issuerId()) + || !(SOURCE_SCOPE_PREFIX + exactIssuer).equals(event.sourceScope()) + || !currentSnapshot.outboxStreamKey().equals(event.outboxStreamKey()) + || !Long.toString(requestedSequence).equals(event.outboxSequence()) + || new BigInteger(event.outboxSequence()) + .compareTo(BigInteger.valueOf(currentSnapshot.outboxSequence())) + > 0 + || new BigInteger(event.issuerAuthGeneration()) + .compareTo(BigInteger.valueOf(currentSnapshot.issuerAuthGeneration())) + > 0 + || new BigInteger(event.sourceVersion()) + .compareTo(BigInteger.valueOf(currentSnapshot.sourceVersion())) + > 0) { + throw new IllegalStateException("Requested issuer event differs from its exact selector"); + } + if (requestedSequence == currentSnapshot.outboxSequence() + && (currentSnapshot.latestEvent().isEmpty() + || !sameCanonicalEvent(event, currentSnapshot.latestEvent().orElseThrow()))) { + throw new IllegalStateException("Requested latest issuer event differs from its checkpoint"); + } + } + + private static void verifyCompleteEvent(IssuerGenerationAuthorityEvent event) { + if (event == null) { + throw new IllegalStateException("Issuer authority event is absent"); + } + IssuerGenerationAuthorityEvent verified = + IssuerGenerationAuthorityEventV1Codec.verify(event.canonicalJson()); + if (!sameCanonicalEvent(event, verified) + || !event.eventId().equals(EVENT_ID_PREFIX + event.requestId())) { + throw new IllegalStateException( + "Issuer authority event is not complete canonical source data"); + } + UUID eventRequestId; + try { + eventRequestId = UUID.fromString(event.requestId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Issuer authority event request identity is malformed", malformed); + } + if (new UUID(0L, 0L).equals(eventRequestId) + || !eventRequestId.toString().equals(event.requestId())) { + throw new IllegalStateException("Issuer authority event request identity is noncanonical"); + } + } + + private static boolean sameCanonicalEvent( + IssuerGenerationAuthorityEvent first, IssuerGenerationAuthorityEvent second) { + return first != null + && second != null + && first.schemaVersion().equals(second.schemaVersion()) + && first.eventType().equals(second.eventType()) + && first.eventId().equals(second.eventId()) + && first.requestId().equals(second.requestId()) + && first.issuerId().equals(second.issuerId()) + && first.sourceScope().equals(second.sourceScope()) + && first.outboxStreamKey().equals(second.outboxStreamKey()) + && first.outboxSequence().equals(second.outboxSequence()) + && first.issuerAuthGeneration().equals(second.issuerAuthGeneration()) + && first.sourceVersion().equals(second.sourceVersion()) + && first.eventDigest().equals(second.eventDigest()) + && first.canonicalJson().equals(second.canonicalJson()) + && MessageDigest.isEqual(first.canonicalJsonUtf8(), second.canonicalJsonUtf8()); + } + + private static Status.Code sourceFailureCode(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof TransientDataAccessException || cause instanceof SQLTransientException) { + return Status.Code.UNAVAILABLE; + } + } + return Status.Code.FAILED_PRECONDITION; + } + + private static boolean isExactIssuerMismatch(Throwable failure) { + return failure instanceof AccountIssuerAuthorityEventProducer.IssuerMismatchException; + } + + private record RequestSelection( + String issuerId, String requestId, Optional requestedSequence) { + private RequestSelection { + Objects.requireNonNull(issuerId, "issuerId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(requestedSequence, "requestedSequence"); + } + } + + private static final class InvalidRequestException extends RuntimeException { + private static final long serialVersionUID = 1L; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index 3ff01479e9..72e48dffa1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -10,7 +10,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -102,6 +104,157 @@ void exactRetryRecoversLostResponseAndOriginalEventAfterLaterAdvance() { assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(2L); } + @Test + void exactHistoricalReadReturnsTheRequestedEventAndCurrentSourceCheckpoint() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + UUID firstRequest = UUID.randomUUID(); + IssuerGenerationAuthorityEvent first = + fixture.producer().advance(ISSUER_ID, firstRequest, 1L, 1L); + IssuerGenerationAuthorityEvent second = + fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 2L, 2L); + + AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback readback = + fixture.producer().readCommittedEvent(ISSUER_ID, 1L); + + assertSameEvent(first, readback.requestedEvent()); + assertThat(readback.currentSnapshot().issuerAuthGeneration()).isEqualTo(3L); + assertThat(readback.currentSnapshot().sourceVersion()).isEqualTo(3L); + assertThat(readback.currentSnapshot().outboxSequence()).isEqualTo(2L); + assertThat(readback.currentSnapshot().latestEvent()).isPresent(); + assertSameEvent(second, readback.currentSnapshot().latestEvent().orElseThrow()); + } + + @Test + void historicalReadDenialsDoNotMutateAndMissingRetainedEventFailsClosed() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L); + fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 2L, 2L); + StoredState before = snapshot(fixture); + + assertThatThrownBy( + () -> fixture.producer().readCommittedEvent("https://other.example.test/issuer", 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixture.producer().readCommittedEvent(ISSUER_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixture.producer().readCommittedEvent(ISSUER_ID, 3L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ahead of the current checkpoint"); + assertThat(snapshot(fixture)).isEqualTo(before); + + Fixture missingHistorical = newFixture(); + seedIssuer(missingHistorical); + missingHistorical.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L); + missingHistorical.producer().advance(ISSUER_ID, UUID.randomUUID(), 2L, 2L); + missingHistorical + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "DISABLE TRIGGER account_authority_outbox_event_update"); + missingHistorical + .setupDsl() + .execute( + "DELETE FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + STREAM_KEY); + missingHistorical + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "ENABLE TRIGGER account_authority_outbox_event_update"); + StoredState afterFixtureCorruption = snapshot(missingHistorical); + + assertThatThrownBy(() -> missingHistorical.producer().readCommittedEvent(ISSUER_ID, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained issuer event is missing"); + assertThat(snapshot(missingHistorical)).isEqualTo(afterFixtureCorruption); + + Fixture malformedHistorical = newFixture(); + seedIssuer(malformedHistorical); + malformedHistorical.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L); + malformedHistorical.producer().advance(ISSUER_ID, UUID.randomUUID(), 2L, 2L); + malformedHistorical + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "DISABLE TRIGGER account_authority_outbox_event_update"); + malformedHistorical + .setupDsl() + .execute( + "UPDATE account_authority_outbox_events SET payload = ? " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + "not-json".getBytes(java.nio.charset.StandardCharsets.UTF_8), + STREAM_KEY); + malformedHistorical + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "ENABLE TRIGGER account_authority_outbox_event_update"); + StoredState afterMalformedFixture = snapshot(malformedHistorical); + + assertThatThrownBy(() -> malformedHistorical.producer().readCommittedEvent(ISSUER_ID, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event JSON is malformed"); + assertThat(snapshot(malformedHistorical)).isEqualTo(afterMalformedFixture); + } + + @Test + void concurrentHistoricalReadWaitsForIssuerRowFenceAndReturnsCommittedCurrentState() + throws Exception { + Fixture fixture = newFixture(); + seedIssuer(fixture); + IssuerGenerationAuthorityEvent first = + fixture.producer().advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L); + UUID secondRequest = UUID.randomUUID(); + CountDownLatch sourceLocked = new CountDownLatch(1); + CountDownLatch releaseAdvance = new CountDownLatch(1); + CountDownLatch readStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future advance = + executor.submit( + () -> + transaction( + fixture.transaction(), + () -> { + ScopeState current = + fixture.generations().read(AuthorityScope.issuer(ISSUER_ID)); + sourceLocked.countDown(); + await(releaseAdvance); + ScopeState advanced = fixture.generations().advance(current, null); + appendSeedEvent( + fixture, + secondRequest, + advanced.generation(), + advanced.sourceVersion()); + return null; + })); + assertThat(sourceLocked.await(20, TimeUnit.SECONDS)).isTrue(); + Future read = + executor.submit( + () -> { + readStarted.countDown(); + return fixture.producer().readCommittedEvent(ISSUER_ID, 1L); + }); + assertThat(readStarted.await(20, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> read.get(300, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + + releaseAdvance.countDown(); + advance.get(45, TimeUnit.SECONDS); + AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback readback = + read.get(45, TimeUnit.SECONDS); + assertSameEvent(first, readback.requestedEvent()); + assertThat(readback.currentSnapshot().issuerAuthGeneration()).isEqualTo(3L); + assertThat(readback.currentSnapshot().sourceVersion()).isEqualTo(3L); + assertThat(readback.currentSnapshot().outboxSequence()).isEqualTo(2L); + } finally { + releaseAdvance.countDown(); + executor.shutdownNow(); + } + } + @Test void concurrentExactRequestSerializesAndCommitsOneSourceEvent() throws Exception { Fixture fixture = newFixture(); @@ -243,6 +396,9 @@ void positiveReadbackRejectsSourceCountersThatDifferFromLatestEvent() { assertThatThrownBy(() -> fixture.producer().readCurrent(ISSUER_ID)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Latest issuer source event differs"); + assertThatThrownBy(() -> fixture.producer().readCommittedEvent(ISSUER_ID, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Latest issuer source event differs"); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java index 133c56a382..9841105314 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java @@ -34,6 +34,9 @@ void requestedIssuerMismatchIsRejectedBeforeDatabaseOrTransactionManagerInteract assertThatThrownBy(() -> producer.readCurrent(OTHER_ISSUER_ID)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact configured issuer"); + assertThatThrownBy(() -> producer.readCommittedEvent(OTHER_ISSUER_ID, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact configured issuer"); collaborators.verifyUnused(); } @@ -52,6 +55,9 @@ void nilRequestAndNonpositiveExpectedCountersAreRejectedBeforePersistence() { assertThatThrownBy(() -> producer.advance(ISSUER_ID, UUID.randomUUID(), 1L, 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be positive"); + assertThatThrownBy(() -> producer.readCommittedEvent(ISSUER_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence must be positive"); collaborators.verifyUnused(); } @@ -115,6 +121,9 @@ void ambientActualTransactionIsRejectedAndThreadStateIsRestored() { assertThatThrownBy(() -> producer.readCurrent(ISSUER_ID)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("without an ambient transaction"); + assertThatThrownBy(() -> producer.readCommittedEvent(ISSUER_ID, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); assertThatThrownBy(() -> producer.advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("without an ambient transaction"); @@ -188,6 +197,56 @@ void positiveSnapshotRejectsMissingOrMismatchedLatestEvent() { assertThat(validShape.latestEvent().orElseThrow()).isSameAs(matchingEvent); } + @Test + void historicalReadbackBindsAnOlderExactEventToTheCurrentSnapshot() { + IssuerGenerationAuthorityEvent historical = event(ISSUER_ID, UUID.randomUUID(), 1L, 2L, 3L); + IssuerGenerationAuthorityEvent latest = event(ISSUER_ID, UUID.randomUUID(), 4L, 5L, 7L); + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot current = + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 5L, 7L, STREAM_KEY, 4L, Optional.of(latest)); + + AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback readback = + new AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback(current, historical); + + assertThat(readback.currentSnapshot()).isSameAs(current); + assertThat(readback.requestedEvent()).isSameAs(historical); + } + + @Test + void historicalReadbackRejectsWrongIssuerStreamAndEventsAheadOfCurrentSnapshot() { + IssuerGenerationAuthorityEvent latest = event(ISSUER_ID, UUID.randomUUID(), 2L, 3L, 4L); + IssuerGenerationAuthorityEvent differentLatest = + event(ISSUER_ID, UUID.randomUUID(), 2L, 3L, 4L); + AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot current = + new AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot( + ISSUER_ID, 3L, 4L, STREAM_KEY, 2L, Optional.of(latest)); + + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback( + current, event(OTHER_ISSUER_ID, UUID.randomUUID(), 1L, 2L, 2L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not bind"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback( + current, event(ISSUER_ID, UUID.randomUUID(), 3L, 3L, 4L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ahead of the current snapshot"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback( + current, event(ISSUER_ID, UUID.randomUUID(), 1L, 4L, 4L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ahead of the current snapshot"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback( + current, differentLatest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the current snapshot checkpoint"); + } + private AccountIssuerAuthorityEventProducer newProducer( String issuerId, Collaborators collaborators) { return new AccountIssuerAuthorityEventProducer( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java new file mode 100644 index 0000000000..d2e0d73468 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java @@ -0,0 +1,374 @@ +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.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityGrpcService; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.dao.TransientDataAccessResourceException; + +class AccountIssuerAuthorityGrpcServiceTest { + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String SOURCE_SCOPE = "issuer/" + ISSUER_ID; + private static final String STREAM_KEY = "account:auth-authority:v1:" + SOURCE_SCOPE; + private static final String NAMESPACE = "firemud-test"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String REQUEST_ID = "f50e8400-e29b-41d4-a716-446655440000"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity(GAME_SESSION_URI, NAMESPACE, "game-session-service"); + + @Test + void constructorRequiresProducerAndValidWorkloadNamespace() { + assertThatThrownBy(() -> new AccountIssuerAuthorityGrpcService(null, NAMESPACE)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("producer"); + assertThatThrownBy( + () -> new AccountIssuerAuthorityGrpcService(mockProducer(), "Invalid_Namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + } + + @Test + void exactCertificateDerivedCallerIsCheckedBeforeAnySourceAccess() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerAuthorityGrpcService service = newService(producer); + ReadIssuerAuthorityForRuntimeRequest request = validRequest(); + + Outcome wrongService = + invoke( + service, + request, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service")); + assertFailure(wrongService, Status.Code.PERMISSION_DENIED); + + Outcome wrongNamespace = + invoke( + service, + request, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other-test/sa/game-session-service", + "other-test", + "game-session-service")); + assertFailure(wrongNamespace, Status.Code.PERMISSION_DENIED); + + verifyNoInteractions(producer); + } + + @Test + void missingCallerIsDeniedBeforeRequestParsingOrSourceAccess() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerAuthorityGrpcService service = newService(producer); + ReadIssuerAuthorityForRuntimeRequest malformed = + ReadIssuerAuthorityForRuntimeRequest.newBuilder().setIssuerId(" ").build(); + + Outcome outcome = invokeWithoutPeer(service, malformed); + + assertFailure(outcome, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(producer); + } + + @Test + void unknownFieldsMalformedRequestIdentityAndInvalidSelectorsFailBeforeSourceAccess() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerAuthorityGrpcService service = newService(producer); + ReadIssuerAuthorityForRuntimeRequest valid = validRequest(); + List invalidRequests = + List.of( + valid.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1L) + .build()) + .build()) + .build(), + valid.toBuilder().setRequestId("F50E8400-E29B-41D4-A716-446655440000").build(), + valid.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + valid.toBuilder().setRequestId("f50e8400-e29b-41d4-a716-446655440000 ").build(), + valid.toBuilder().setIssuerId(" ").build(), + valid.toBuilder().setRequestedOutboxSequence("0").build(), + valid.toBuilder().setRequestedOutboxSequence("01").build(), + valid.toBuilder().setRequestedOutboxSequence("+1").build(), + valid.toBuilder().setRequestedOutboxSequence("-1").build(), + valid.toBuilder().setRequestedOutboxSequence("9223372036854775808").build()); + + for (ReadIssuerAuthorityForRuntimeRequest invalidRequest : invalidRequests) { + Outcome outcome = + invoke(service, invalidRequest, GAME_SESSION_PEER); + assertFailure(outcome, Status.Code.INVALID_ARGUMENT); + } + + verifyNoInteractions(producer); + } + + @Test + void canonicalBaselineCurrentReadOmitsAllEventFields() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + IssuerAuthoritySnapshot baseline = newSnapshot(1L, 1L, 0L, Optional.empty()); + when(producer.readCurrent(ISSUER_ID)).thenReturn(baseline); + AccountIssuerAuthorityGrpcService service = newService(producer); + + Outcome outcome = + invoke(service, validRequest(), GAME_SESSION_PEER); + + ReadIssuerAuthorityForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getSchemaVersion()).isEqualTo("account-auth-issuer-source-readback/v1"); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(response.hasRequestedEventCanonicalJson()).isFalse(); + assertThat(response.getSourceSnapshot().getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(response.getSourceSnapshot().getSourceScope()).isEqualTo(SOURCE_SCOPE); + assertThat(response.getSourceSnapshot().getOutboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(response.getSourceSnapshot().getIssuerAuthGeneration()).isEqualTo("1"); + assertThat(response.getSourceSnapshot().getSourceVersion()).isEqualTo("1"); + assertThat(response.getSourceSnapshot().getOutboxSequence()).isEqualTo("0"); + assertThat(response.getSourceSnapshot().hasLatestEventCanonicalJson()).isFalse(); + verify(producer).readCurrent(ISSUER_ID); + } + + @Test + void positiveCurrentReadReturnsExactLatestCanonicalEvent() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + IssuerGenerationAuthorityEvent latest = event(REQUEST_ID, 1L, 2L, 2L); + IssuerAuthoritySnapshot current = newSnapshot(2L, 2L, 1L, Optional.of(latest)); + when(producer.readCurrent(ISSUER_ID)).thenReturn(current); + AccountIssuerAuthorityGrpcService service = newService(producer); + + Outcome outcome = + invoke(service, validRequest(), GAME_SESSION_PEER); + + ReadIssuerAuthorityForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getSourceSnapshot().hasLatestEventCanonicalJson()).isTrue(); + assertThat(response.getSourceSnapshot().getLatestEventCanonicalJson()) + .isEqualTo(latest.canonicalJson()); + assertThat(response.hasRequestedEventCanonicalJson()).isFalse(); + verify(producer).readCurrent(ISSUER_ID); + } + + @Test + void historicalReadPreservesCompleteSelectedEventAndCurrentCheckpointSeparately() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + IssuerGenerationAuthorityEvent requested = + event("f50e8400-e29b-41d4-a716-446655440001", 1L, 2L, 2L); + IssuerGenerationAuthorityEvent latest = + event("f50e8400-e29b-41d4-a716-446655440002", 2L, 3L, 3L); + IssuerAuthoritySnapshot current = newSnapshot(3L, 3L, 2L, Optional.of(latest)); + when(producer.readCommittedEvent(ISSUER_ID, 1L)) + .thenReturn(new IssuerAuthorityEventReadback(current, requested)); + AccountIssuerAuthorityGrpcService service = newService(producer); + ReadIssuerAuthorityForRuntimeRequest request = + validRequest().toBuilder().setRequestedOutboxSequence("1").build(); + + Outcome outcome = + invoke(service, request, GAME_SESSION_PEER); + + ReadIssuerAuthorityForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(response.getSourceSnapshot().getOutboxSequence()).isEqualTo("2"); + assertThat(response.getSourceSnapshot().getLatestEventCanonicalJson()) + .isEqualTo(latest.canonicalJson()); + assertThat(response.hasRequestedEventCanonicalJson()).isTrue(); + assertThat(response.getRequestedEventCanonicalJson()).isEqualTo(requested.canonicalJson()); + assertThat(response.getRequestedEventCanonicalJson()) + .contains("\"eventId\":\"account-issuer-authority-event-v1:") + .contains("\"eventDigest\":\"sha256:") + .doesNotContain("authorityTuple", "issuanceFence", "outboxCheckpoints"); + verify(producer).readCommittedEvent(ISSUER_ID, 1L); + } + + @Test + void wrongHistoricalEventSelectorFailsWithoutPartialContent() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + IssuerGenerationAuthorityEvent selected = event(REQUEST_ID, 2L, 3L, 3L); + IssuerGenerationAuthorityEvent latest = event(REQUEST_ID, 2L, 3L, 3L); + IssuerAuthoritySnapshot current = newSnapshot(3L, 3L, 2L, Optional.of(latest)); + when(producer.readCommittedEvent(ISSUER_ID, 1L)) + .thenReturn(new IssuerAuthorityEventReadback(current, selected)); + AccountIssuerAuthorityGrpcService service = newService(producer); + + Outcome outcome = + invoke( + service, + validRequest().toBuilder().setRequestedOutboxSequence("1").build(), + GAME_SESSION_PEER); + + assertFailure(outcome, Status.Code.FAILED_PRECONDITION); + } + + @Test + void ownerContradictionAndTransientAccessFailureReturnTerminalSanitizedStatuses() { + AccountIssuerAuthorityEventProducer contradictoryProducer = mockProducer(); + when(contradictoryProducer.readCurrent(ISSUER_ID)) + .thenThrow(new IllegalStateException("internal source payload details")); + AccountIssuerAuthorityGrpcService contradictoryService = newService(contradictoryProducer); + Outcome contradiction = + invoke(contradictoryService, validRequest(), GAME_SESSION_PEER); + assertFailure(contradiction, Status.Code.FAILED_PRECONDITION); + assertThat(contradiction.error().getDescription()) + .doesNotContain("internal source payload details"); + + AccountIssuerAuthorityEventProducer transientProducer = mockProducer(); + when(transientProducer.readCurrent(ISSUER_ID)) + .thenThrow(new TransientDataAccessResourceException("database access detail")); + AccountIssuerAuthorityGrpcService transientService = newService(transientProducer); + Outcome unavailable = + invoke(transientService, validRequest(), GAME_SESSION_PEER); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(unavailable.error().getDescription()).doesNotContain("database access detail"); + } + + @Test + void exactConfiguredIssuerRejectionIsInvalidArgument() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + when(producer.readCurrent("https://other.example.test/issuer")) + .thenThrow(new AccountIssuerAuthorityEventProducer.IssuerMismatchException()); + AccountIssuerAuthorityGrpcService service = newService(producer); + ReadIssuerAuthorityForRuntimeRequest request = + validRequest().toBuilder().setIssuerId("https://other.example.test/issuer").build(); + + Outcome outcome = + invoke(service, request, GAME_SESSION_PEER); + + assertFailure(outcome, Status.Code.INVALID_ARGUMENT); + } + + private static AccountIssuerAuthorityGrpcService newService( + AccountIssuerAuthorityEventProducer producer) { + return new AccountIssuerAuthorityGrpcService(producer, NAMESPACE); + } + + private static AccountIssuerAuthorityEventProducer mockProducer() { + return mock(AccountIssuerAuthorityEventProducer.class); + } + + private static ReadIssuerAuthorityForRuntimeRequest validRequest() { + return ReadIssuerAuthorityForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setRequestId(REQUEST_ID) + .build(); + } + + private static IssuerAuthoritySnapshot newSnapshot( + long generation, + long sourceVersion, + long sequence, + Optional latestEvent) { + return new IssuerAuthoritySnapshot( + ISSUER_ID, generation, sourceVersion, STREAM_KEY, sequence, latestEvent); + } + + private static IssuerGenerationAuthorityEvent event( + String eventRequestId, long sequence, long generation, long sourceVersion) { + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + eventRequestId, + "requestId", + eventRequestId, + "issuerId", + ISSUER_ID, + "sourceScope", + SOURCE_SCOPE, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private static Outcome invoke( + AccountIssuerAuthorityGrpcService service, + ReadIssuerAuthorityForRuntimeRequest request, + GrpcPeerIdentity peerIdentity) { + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity); + Context previous = peerContext.attach(); + try { + RecordingObserver observer = new RecordingObserver<>(); + service.readIssuerAuthorityForRuntime(request, observer); + return observer.outcome(); + } finally { + peerContext.detach(previous); + } + } + + private static Outcome invokeWithoutPeer( + AccountIssuerAuthorityGrpcService service, ReadIssuerAuthorityForRuntimeRequest request) { + RecordingObserver observer = new RecordingObserver<>(); + service.readIssuerAuthorityForRuntime(request, observer); + return observer.outcome(); + } + + private static T assertSuccess(Outcome outcome) { + assertThat(outcome.error()).isNull(); + assertThat(outcome.completed()).isTrue(); + assertThat(outcome.responses()).hasSize(1); + return outcome.responses().get(0); + } + + private static void assertFailure(Outcome outcome, Status.Code expectedCode) { + assertThat(outcome.error()).isNotNull(); + assertThat(outcome.error().getCode()).isEqualTo(expectedCode); + assertThat(outcome.responses()).isEmpty(); + assertThat(outcome.completed()).isFalse(); + } + + private record Outcome(List responses, Status error, boolean completed) {} + + private static final class RecordingObserver implements StreamObserver { + private final List responses = new ArrayList<>(); + private Status error; + private boolean completed; + + @Override + public void onNext(T value) { + responses.add(value); + } + + @Override + public void onError(Throwable throwable) { + Status received = Status.fromThrowable(throwable); + error = Status.fromCode(received.getCode()).withDescription(received.getDescription()); + } + + @Override + public void onCompleted() { + completed = true; + } + + private Outcome outcome() { + return new Outcome<>(List.copyOf(responses), error, completed); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java index 3a88de579d..6f5a9ae2ba 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java @@ -3,12 +3,14 @@ import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import java.util.Map; +import java.util.UUID; import org.springframework.util.StringUtils; /** Issues and validates signed gameplay-session attestations for delegated gameplay RPCs. */ public class GameplaySessionAttestationService { public static final String GAMEPLAY_SESSION = "GAMEPLAY_SESSION"; public static final String INTERNAL_PROBE = "INTERNAL_PROBE"; + private static final UUID NIL_UUID = new UUID(0L, 0L); private final JwtUtil jwtUtil; @@ -30,7 +32,7 @@ public String issueGameplaySessionAttestation( String normalizedRoomInstanceId = requireOptionalCanonicalRuntimeRoomId(roomInstanceId); requireText(tenantId, "tenantId"); requireText(sessionId, "sessionId"); - requireText(accountId, "accountId"); + requireCanonicalAccountUuidForIssuance(accountId); requireText(characterId, "characterId"); requireText(gameInstanceId, "gameInstanceId"); requireText(worldSlug, "worldSlug"); @@ -166,13 +168,13 @@ public void requireGameplaySessionMatch( } requirePositiveId(claims.tenantId(), "tenantId"); requirePositiveId(claims.sessionId(), "sessionId"); - requirePositiveId(claims.accountId(), "accountId"); + requireCanonicalAccountUuidClaim(claims.accountId()); requirePositiveId(claims.characterId(), "characterId"); requirePositiveId(claims.gameInstanceId(), "gameInstanceId"); requirePositiveId(claims.pointerVersion(), "pointerVersion"); requirePositiveEquals(claims.tenantId(), tenantId, "tenantId"); requireOptionalPositiveEquals(claims.sessionId(), sessionId, "sessionId"); - requireOptionalPositiveEquals(claims.accountId(), accountId, "accountId"); + requireOptionalAccountEquals(claims.accountId(), accountId); requireOptionalPositiveEquals(claims.characterId(), characterId, "characterId"); requireOptionalPositiveEquals(claims.gameInstanceId(), gameInstanceId, "gameInstanceId"); // roomInstanceId remains a routed room identifier string; keep text equality here. @@ -186,6 +188,9 @@ public void requireGameplaySessionMatch( public void requireGameplayOrProbeMatch( String token, String tenantId, String gameInstanceId, String roomInstanceId) { GameplaySessionAttestationClaims claims = requireValid(token); + if (GAMEPLAY_SESSION.equals(claims.attestationType())) { + requireCanonicalAccountUuidClaim(claims.accountId()); + } requirePositiveEquals(claims.tenantId(), tenantId, "tenantId"); requirePositiveEquals(claims.gameInstanceId(), gameInstanceId, "gameInstanceId"); // roomInstanceId remains a routed room identifier string; keep text equality for probe tokens. @@ -222,6 +227,13 @@ private void requireOptionalPositiveEquals(String actual, String expected, Strin } } + private void requireOptionalAccountEquals(String actual, String expected) { + if (StringUtils.hasText(expected)) { + requireCanonicalAccountUuidClaim(expected); + requireEquals(actual, expected, "accountId"); + } + } + private void requireClaimsType(GameplaySessionAttestationClaims claims, String expectedType) { if (claims == null || !expectedType.equals(claims.attestationType())) { throw new GameplaySessionAttestationException( @@ -245,6 +257,31 @@ private long requirePositiveId(String value, String fieldName) { } } + private void requireCanonicalAccountUuidForIssuance(String accountId) { + if (!isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + } + + private void requireCanonicalAccountUuidClaim(String accountId) { + if (!isCanonicalNonNilUuid(accountId)) { + throw new GameplaySessionAttestationException( + "SESSION_ATTESTATION_INVALID", "Malformed claim: accountId"); + } + } + + private boolean isCanonicalNonNilUuid(String value) { + if (!StringUtils.hasText(value)) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } + private String requireClaim(Claims claims, String name) { try { return JwtClaims.requireClaim(claims, name); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java index dd54a8783c..ba018790e3 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java @@ -10,6 +10,12 @@ class GameplaySessionAttestationServiceTest { + private static final String ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String OTHER_ACCOUNT_UUID = "a7e0feac-60ab-4fd1-9002-0ad38d585db0"; + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final List INVALID_ACCOUNT_IDS = + List.of("7", "not-a-uuid", "123E4567-E89B-12D3-A456-426614174000", NIL_UUID); + private final JwtUtil jwtUtil; private final GameplaySessionAttestationService service; @@ -22,23 +28,80 @@ class GameplaySessionAttestationServiceTest { void requireGameplaySessionMatchAllowsOmittedOptionalDimensions() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); assertDoesNotThrow( () -> service.requireGameplaySessionMatch(token, "22", null, null, "123", "1", "R-1021")); } + @Test + void requireGameplaySessionMatchAcceptsUuidAccountWithNumericRuntimeTenant() { + String token = + service.issueGameplaySessionAttestation( + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + + assertDoesNotThrow( + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + } + + @Test + void issueGameplaySessionAttestationRejectsInvalidAccountIds() { + for (String accountId : INVALID_ACCOUNT_IDS) { + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> + service.issueGameplaySessionAttestation( + "22", + "41", + accountId, + "123", + "1", + "R-1021", + "demo", + "production", + "17", + "SHARED")); + + assertEquals("accountId must be a canonical non-nil UUID", ex.getMessage()); + } + } + + @Test + void requireGameplaySessionMatchRejectsInvalidAccountIdClaims() { + for (String accountId : INVALID_ACCOUNT_IDS) { + GameplaySessionAttestationException ex = + assertThrows( + GameplaySessionAttestationException.class, + () -> + service.requireGameplaySessionMatch( + gameplayTokenWithAccountId(accountId), + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021")); + + assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); + assertEquals("Malformed claim: accountId", ex.getMessage()); + } + } + @Test void requireGameplaySessionMatchStillRejectsProvidedMismatchedDimensions() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "99", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", OTHER_ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_MISMATCH", ex.getCode()); assertEquals("Gameplay session attestation does not match accountId", ex.getMessage()); @@ -48,23 +111,26 @@ void requireGameplaySessionMatchStillRejectsProvidedMismatchedDimensions() { void requireGameplaySessionMatchAllowsAlphanumericRoomInstanceId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); assertDoesNotThrow( - () -> service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); } @Test void requireGameplaySessionMatchRejectsMismatchedAlphanumericRoomInstanceId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-2045")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-2045")); assertEquals("SESSION_ATTESTATION_MISMATCH", ex.getCode()); assertEquals("Gameplay session attestation does not match roomInstanceId", ex.getMessage()); @@ -79,7 +145,7 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "room-1021"), @@ -92,7 +158,8 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("roomInstanceId must be a runtime room id like R-1021", ex.getMessage()); @@ -102,7 +169,7 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( @@ -112,7 +179,7 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { token, "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "R-1021", @@ -129,12 +196,14 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { void requireGameplaySessionMatchRejectsZeroTenantIdClaim() { String token = service.issueGameplaySessionAttestation( - "0", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "0", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, - () -> service.requireGameplaySessionMatch(token, "0", "41", "7", "123", "1", "R-1021")); + () -> + service.requireGameplaySessionMatch( + token, "0", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Invalid claim: tenantId", ex.getMessage()); @@ -144,13 +213,14 @@ void requireGameplaySessionMatchRejectsZeroTenantIdClaim() { void requireGameplaySessionMatchRejectsZeroPointerVersionClaim() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "0", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "0", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Invalid claim: pointerVersion", ex.getMessage()); @@ -165,7 +235,7 @@ void requireGameplaySessionMatchRejectsNonNumericClaimId() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "abc"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -178,7 +248,8 @@ void requireGameplaySessionMatchRejectsNonNumericClaimId() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Malformed claim: characterId", ex.getMessage()); @@ -193,7 +264,7 @@ void requireGameplaySessionMatchRejectsSubjectClaimMismatch() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -206,17 +277,18 @@ void requireGameplaySessionMatchRejectsSubjectClaimMismatch() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Gameplay session attestation subject does not match claims", ex.getMessage()); } @Test - void requireGameplaySessionMatchRejectsNonPositiveExpectedAccountId() { + void requireGameplaySessionMatchRejectsMalformedExpectedAccountId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( @@ -225,7 +297,7 @@ void requireGameplaySessionMatchRejectsNonPositiveExpectedAccountId() { service.requireGameplaySessionMatch(token, "22", null, "0", "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); - assertEquals("Invalid claim: accountId", ex.getMessage()); + assertEquals("Malformed claim: accountId", ex.getMessage()); } @Test @@ -235,6 +307,19 @@ void requireGameplayOrProbeMatchAcceptsProbeAttestation() { assertDoesNotThrow(() -> service.requireGameplayOrProbeMatch(token, "22", "1", "R-1021")); } + @Test + void requireGameplayOrProbeMatchRejectsInvalidAccountIdOnGameplayAttestation() { + GameplaySessionAttestationException ex = + assertThrows( + GameplaySessionAttestationException.class, + () -> + service.requireGameplayOrProbeMatch( + gameplayTokenWithAccountId("7"), "22", "1", "R-1021")); + + assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); + assertEquals("Malformed claim: accountId", ex.getMessage()); + } + @Test void requireGameplayOrProbeMatchRejectsMalformedTenantId() { String token = @@ -331,7 +416,7 @@ void issueGameplaySessionAttestationRejectsLegacyRuntimeRoomId() { service.issueGameplaySessionAttestation( "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "room-1021", @@ -371,7 +456,16 @@ void requireAdmittedRoutingBundleAcceptsGameplayAttestationWithRoutingClaims() { GameplaySessionAttestationClaims claims = service.requireValid( service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED")); + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021", + "demo", + "production", + "17", + "SHARED")); assertDoesNotThrow(() -> service.requireAdmittedRoutingBundle(claims)); } @@ -386,7 +480,7 @@ void requireAdmittedRoutingBundleRejectsGameplayAttestationMissingPointerVersion Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -411,7 +505,16 @@ void issueGameplaySessionAttestationRejectsMissingRoutingBundleClaims() { IllegalArgumentException.class, () -> service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", null, "production", null, "SHARED")); + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021", + null, + "production", + null, + "SHARED")); assertEquals("worldSlug must not be blank", ex.getMessage()); } @@ -425,7 +528,7 @@ void requireValidUsesCanonicalIterableClaimParsing() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", List.of(" ", "22")), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", List.of("", "R-1021")), @@ -440,4 +543,21 @@ void requireValidUsesCanonicalIterableClaimParsing() { assertEquals("R-1021", claims.roomInstanceId()); assertEquals("demo", claims.worldSlug()); } + + private String gameplayTokenWithAccountId(String accountId) { + return jwtUtil.generateToken( + "gameplay-session:41", + Map.ofEntries( + Map.entry("attestationType", "GAMEPLAY_SESSION"), + Map.entry("tenantId", "22"), + Map.entry("sessionId", "41"), + Map.entry("accountId", accountId), + Map.entry("characterId", "123"), + Map.entry("gameInstanceId", "1"), + Map.entry("roomInstanceId", "R-1021"), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("pointerVersion", "17"), + Map.entry("playableStateScope", "SHARED"))); + } } diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/README.md b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/README.md new file mode 100644 index 0000000000..1a146d09bb --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/README.md @@ -0,0 +1,7 @@ +# Issuer Authority gRPC mTLS Test Certificates + +PUBLIC TEST KEYS ONLY. These certificates and private keys exist only to prove the Account issuer-authority gRPC peer-identity boundary in tests. Never use or mount them as runtime or deployed credentials. Production material must be issued separately. + +The fixture CA signs leaves with one exact FireMUD SPIFFE URI SAN each. `account.crt` identifies `spiffe://firemud/ns/test/sa/account-service`; `game-session.crt` identifies `spiffe://firemud/ns/test/sa/game-session-service`; `wrong-service.crt` identifies `spiffe://firemud/ns/test/sa/game-design-service`; `wrong-namespace.crt` identifies `spiffe://firemud/ns/other-test/sa/game-session-service`; and `wrong-account-namespace.crt` identifies `spiffe://firemud/ns/other-test/sa/account-service`. The wrong-service and wrong-namespace leaves provide trusted but unauthorized clients; the Account leaf with the wrong namespace provides a trusted server identity with only the namespace changed. Every leaf also has `DNS:localhost` and `IP:127.0.0.1` SANs for the loopback socket. Leaves are valid for both TLS server and client authentication. + +The fixtures were generated together with OpenSSL as a test-only CA and RSA leaf keypairs. The CA private key was not retained in the fixture directory. All leaves expire on `2036-09-29` UTC; regenerate this set before that date if the tests remain in use. Verify each leaf with `openssl verify -CAfile ca.crt .crt`, inspect URI SANs with `openssl x509 -in .crt -noout -ext subjectAltName`, and confirm leaf key usage with `openssl x509 -in .crt -noout -ext extendedKeyUsage` after regeneration. diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.crt b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.crt new file mode 100644 index 0000000000..fd290ca1cd --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDlTCCAn2gAwIBAgIUa+6MAfzk1f5+VWQB8TiOdadUQegwDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgRmlyZU1VRCBJc3N1ZXIgQXV0aG9yaXR5IFRlc3QgQ0Ew +HhcNMjYxMDAyMDI1OTM4WhcNMzYwOTI5MDI1OTM4WjASMRAwDgYDVQQDDAdhY2Nv +dW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAouv1GMOmJSsuPU0e +dnrC46Ts78adR+W4bHsqyWhOkzdSEQ3zyhPjQaeiscpor0lQoRz6xHvstoEReIRh +xynhu+U5dub9AkhniqWQiUWoZJqQt4i9ewO2K5aihdcze/Aa9c0MxCUNrwrO5NZl +hUAvDX8IWZ+prrYgA+1aDQ2g4ezaFGP1Xy1JN86kXK/GemXJ2Wrq5Zn5HtJssXRi +s/DBHjL3ZqzLcKdyiEHzzOpDmDX39/VSIoE/Y6S9OC+l7r9WJ79PLFH8vbOHLoGW +FT4DPkQ+l1Fk6rrTpSDo8E7GrqBYFDhj7QNuSqpND0gaEkypr8yOLvUP/pufndtz +ehZLdQIDAQABo4HJMIHGMEcGA1UdEQRAMD6GK3NwaWZmZTovL2ZpcmVtdWQvbnMv +dGVzdC9zYS9hY2NvdW50LXNlcnZpY2WCCWxvY2FsaG9zdIcEfwAAATAMBgNVHRMB +Af8EAjAAMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB +BQUHAwIwHQYDVR0OBBYEFJb4xh3rO1RlMoXphhy3fKE4Zw7yMB8GA1UdIwQYMBaA +FLGSwnBTR11nkQljglqJ/KiI5O5HMA0GCSqGSIb3DQEBCwUAA4IBAQBHBm3x9my3 +hrTIN90M6U3+B1E/QBwFfmqnUmJhY77B4lNC8pMn/ykZw5DDTOE1bJOF3SUCOyB8 +yBhyMmE2woIg3qpVZdn+fgXqMXUBbGT216wshdG5UkN2/JEaddiSoz5eqizCh8qn +jlGAtImzvj55xHEfK4dlh9EE6Wyu6m5twW1OWJBWESYhd+SeXgWlIINQiaNTzmxe +LJasLx03WH+VOvOh8pkG6KUpC25/qj3OWa+YTYEJd/ecaRbWJOSVMJWtjWKXUFuG +65P5IH+AElAqOAKfooNoJrq9uPxpPSOdar80AjdKCHV/qxwM9pep9kYLMX6qht+g +hsLYlfcSZsmW +-----END CERTIFICATE----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.key b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.key new file mode 100644 index 0000000000..6d75c85640 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/account.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCi6/UYw6YlKy49 +TR52esLjpOzvxp1H5bhseyrJaE6TN1IRDfPKE+NBp6KxymivSVChHPrEe+y2gRF4 +hGHHKeG75Tl25v0CSGeKpZCJRahkmpC3iL17A7YrlqKF1zN78Br1zQzEJQ2vCs7k +1mWFQC8NfwhZn6mutiAD7VoNDaDh7NoUY/VfLUk3zqRcr8Z6ZcnZaurlmfke0myx +dGKz8MEeMvdmrMtwp3KIQfPM6kOYNff39VIigT9jpL04L6Xuv1Ynv08sUfy9s4cu +gZYVPgM+RD6XUWTqutOlIOjwTsauoFgUOGPtA25Kqk0PSBoSTKmvzI4u9Q/+m5+d +23N6Fkt1AgMBAAECggEAHjlj6MozAmY2V8z8v8IacZzhD8Jq3zGwuv9GesLNAOac +ZOmPtodl+4Ib3pvMO+h/+sOjidvrmBfto8v7T7VnWTI3LOXBPjEsdD4uyCiSCsfZ +3RKTBEU2AHQbhnTb6jwq5Dq8CY9OMJDyvOVBRC0aDYjphabnFbBX1CKuOAm1NPQt +WB5C1gn82YQdq2UKHYjnQjBxEcfSfNaGCfHXlPvYaGi007Jni/UcENxvNXUwWVY8 +HuW//tM2aHUAolso5OWQF9DrxIt4UVd+JUIfkZvWgj7x35WLGsmMlzu9lxlvhbWI +SvMnSUkzMioG8wEObR10tku5FchVAV8mWkIQ3qaRwQKBgQC1OsSCLYNDad34ACpn +Hb5SQy4igyxemJpK88FfBpYL/qOIMAIXyOPHeU07VeTJAtNElH6ev68IPy0bVngm +UYKzK3MygFhSn8O+5P/qIcuK73hThr7JKFIIt348dFRa+LOyH4iLtUcRdPjEPU30 +W89D4jxX4C7UNjdUpIRFQ8rYeQKBgQDmI4m9+psuM1Nxin4Y8DGe2sKhgqAMYbqT +r84Eq6PI8+iaHgwfigTxDKvdcRNA677Pv5DVZoswM233NuoBvVvc8eqWxCnoLFfP +bi464qgpF88+GU1cisPvwow167jsVtrge0oDKbPC+F5BVYkWjIGnlmMffkoHMN5s +jMQ6MvAD3QKBgC7oZiKXqykQxt5BFLiZ70AVmWRfdWWKtC0ASKXS65VxNFy0qGYF +nkdsMzxPcCdDLvHKSbfHP4Ov7nnr+K9aW60KawfARpwkNCM93Kt6UdfFQezErK8e +W5VcATWempLtWn2ZQdt/cUSodRc+EuZTuSMF9L5+DUDqQ4oKBx5yfJdpAoGAfMmo +VqscmeCazmYaGcukHE7iWlFKF2ymjo41V7L6DGy1I1xHlpJwO4RzbI9zsTAjNuLY +1d3Uez5n0jSkjmzu8s76NOYJEyt4MbG8v5FHPYD7juCJYjScKdWD0XkPvJcb97zi +VPS31HB4K1UGEIP/ia+x79G6skt9T77EaApWusECgYBdnE90TYQ0qnfJ1nx88Iag +s9c7FPkP0F0d57eXcdyeEfboi8aQ3lESBZCiCIR30oRqU1NA7T1YjW+lNsNWJbRS +lOnoPt5FTINnKP0Un/bEJX0P6zkB+vvyLgUCuAiyLQaW145rpa0pIJjTt712C+tG +A3A4aLFtqELKoRF2bMavew== +-----END PRIVATE KEY----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/ca.crt b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/ca.crt new file mode 100644 index 0000000000..951165fbaf --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/ca.crt @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDRzCCAi+gAwIBAgIUCStCkuRq/jV/COozNSbYUZxvj1MwDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgRmlyZU1VRCBJc3N1ZXIgQXV0aG9yaXR5IFRlc3QgQ0Ew +HhcNMjYxMDAyMDI1OTM4WhcNMzYwOTI5MDI1OTM4WjArMSkwJwYDVQQDDCBGaXJl +TVVEIElzc3VlciBBdXRob3JpdHkgVGVzdCBDQTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAOTPYqqP3a71wuX3V38klbbEqEtYGRp4d5CbEkykhn1P5/Of +HMmyhcQ5TJlELO7QhQ9VaC1TXESZhbqNZyV2HZbUCyXFtK9QowLG+Ny8DCD+Z4V/ +mhYL70PjueB1b6NG/9IyO8UHAnFqJY75jUdt+2qEOVdelhdHKCzRmoJnubjvyo64 +kpdYW83hvQaZz7apYZGrGHbPj6VLp17RcXKICyEBpB/+4UBSFIfvwIQzwtXNwDts +UwdVadqY0CXl25Kt/1gdQcPVIUHORLJIcXbrBZFN3lN9JMXWHLCwfJS3GLmne68C +1wnMO8O0SwstGrYMZ6IOT/VLdNgKLTBXfn5F9fsCAwEAAaNjMGEwHQYDVR0OBBYE +FLGSwnBTR11nkQljglqJ/KiI5O5HMB8GA1UdIwQYMBaAFLGSwnBTR11nkQljglqJ +/KiI5O5HMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 +DQEBCwUAA4IBAQA6fU7DL9Y3PIxdD1X8cm5e/45iOTNmME1Mu+w1BZMAP0JhBm9W +EpzaegzfGfufa51bxH2k0xA29TnP5pxt9FGIgtqzXDXaMy/bI0ylgz3d8Knlt6w3 +iD68tZ05PbuGpbs58u7ZEv0yaLWtoWUaYDdA/CPAXO6HYudQaZoaD+gjwbz788qr +wzpC7xPTq/gCzTpuKH93BmgusCuPwVs+jGe0Q9AE2GXqywtqoA5pEW57MP6oeoEb +/fikBpvUMAejLeVG9PJLc85uSH9UjeXaPGuEs1nXMvKY/t3iJlLghdyYV98rJhPM +hbueJVeS9BjkMW5wJMvdIInTBOBuJSfIOSJv +-----END CERTIFICATE----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.crt b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.crt new file mode 100644 index 0000000000..823ea5af28 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDnzCCAoegAwIBAgIUUJgxVUk0Kyes9pWZryM56mbBEb8wDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgRmlyZU1VRCBJc3N1ZXIgQXV0aG9yaXR5IFRlc3QgQ0Ew +HhcNMjYxMDAyMDI1OTM4WhcNMzYwOTI5MDI1OTM4WjAXMRUwEwYDVQQDDAxnYW1l +LXNlc3Npb24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsDGGoszDl +0kHbfbeg9SfwIw++pw8FC+qnZU19MhA/kup0Ppf4oluUDNWj/yIy08bACiTv3uIu +X199gtBkDxMz72bH2aVS5eeAso8jxEaMRTGjhwgP8GqAysjR6PIkYtMnIW4Wc32G +6iClHKnirnl3bWbP6ZHj2NN/lPGj4gJlgv3jDDzhvgGVuO7q64OmzxIhVQ+h8Ds4 +tmESqn0LWLQljaNcVJgDtIeKrkS2dlwToRwVgfBTpWMYa9b5FqNp7at1GxRrb2EY +qaF/4uY6cbja3fa0DSZdqCM61YGI2S/8cbkuOLazqWb3qc5DY31Xfq2Il7XN28eR +HimXZ9q/Nh99AgMBAAGjgc4wgcswTAYDVR0RBEUwQ4Ywc3BpZmZlOi8vZmlyZW11 +ZC9ucy90ZXN0L3NhL2dhbWUtc2Vzc2lvbi1zZXJ2aWNlgglsb2NhbGhvc3SHBH8A +AAEwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYB +BQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBSTpOnNMG1qaIR38q3mF0tonyAnxjAf +BgNVHSMEGDAWgBSxksJwU0ddZ5EJY4JaifyoiOTuRzANBgkqhkiG9w0BAQsFAAOC +AQEANadUwkGnsFZs9zh60VG4UEFs9LdxWtOF8yrY0gAw6D1w9dNZgZE/O/ybirIj +loMH2NVymRUA7OrVF9SlOpwqvki3+6ME7SwKOQPZ8z+mlpn3c0lGzWnlWFLNfcV+ +Y4MRGACeeAhRjPs0O9zb+7eLbtrh47kMhLXKHGfbamx0TqYovPGZm98vJWikhnVl +pTzOzlh8jmmZ/JQq8anRehk0+diiO01yXetrk26fuFqKHD0F6R1Bs1rg+S4TO4G5 +Fjwh6o3LYft5n+VL/UfmuQOwS8WDXDNtL6yzd/1ivPZu78xrv8mV4tPodY3wL1ih +el334eBLBKWojxiL3qHeK/QrGw== +-----END CERTIFICATE----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.key b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.key new file mode 100644 index 0000000000..4bb142821f --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/game-session.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCsDGGoszDl0kHb +fbeg9SfwIw++pw8FC+qnZU19MhA/kup0Ppf4oluUDNWj/yIy08bACiTv3uIuX199 +gtBkDxMz72bH2aVS5eeAso8jxEaMRTGjhwgP8GqAysjR6PIkYtMnIW4Wc32G6iCl +HKnirnl3bWbP6ZHj2NN/lPGj4gJlgv3jDDzhvgGVuO7q64OmzxIhVQ+h8Ds4tmES +qn0LWLQljaNcVJgDtIeKrkS2dlwToRwVgfBTpWMYa9b5FqNp7at1GxRrb2EYqaF/ +4uY6cbja3fa0DSZdqCM61YGI2S/8cbkuOLazqWb3qc5DY31Xfq2Il7XN28eRHimX +Z9q/Nh99AgMBAAECggEADe0To5TbjqK5/3L5396wLKUd42QA2Hr6M7IEt29LtuWk +siOV6AN2T7HJQjTG1x/ivM0lZ8AeBTxljZJ+3TaGKqREaMVSdzcSSc3KPc4nmreI +GNE3gxjF+iZP4oPNQ8o3BroTP+B5xuehHFRJYQaX4OWbVpV0oGF+3xsWgxoqcP5r +ESbpneL7mRXqCvLG3Zrsn/qdFA3yyKTFG6ay2RuUdGXJnGcJ8rpc8w7+GT4xjwBo +ZoCtd9Ob11rZ6a1buRP0dxJ1g+/NS+u0FLMzRtTbTl9xESsQLdMvRXH1eKIuKXkD +NaV3hRUQyWAqu5vs8ued01WnfHDzZu8v4UL2in6sCQKBgQDhEdULMFqO5QHa24U3 +sqLjiSeM6PlzrsteAeAdy/ctLL4rwl+aEMVVVgoeaRN0UQfHeHhgFDvVkNzLaX6k ++DzNHvcCvpO4atg9uLwRFqUuN5Ba/1iXkXdZS9DgxI+ICl/UyP2eIZz9BRePktUR +jAQ/JL2YDp72QFMr+qZK8WCbRQKBgQDDsTWEJwnIwZrmtCOf0ikO576oZHAMlJGK +Vp43J2yNI1a2K+6hCcgoi62vZ+DYhm8iERuQuucHfi/zXrHUROX2hlrczQTopamH +LiiCvJdqCkmFbeEk4ysT3BDBy5qJCmVYwFvX8BBzJMZJXZqp9cxESWhCM6ohif/O +gJe7JG+a2QKBgHHLIUrh7LdYo+JyoN0zTVX7b2q4E/9gPeRO0HBgQp2thIz9Xna3 +yf3GXaFYgQSLP4Kjr0Dsmf/1mRyjPuvLsnoHEN5rWqagJqq2Lyf4qhU+9JZ9id5A +JvaX9Yje+K7Qh/k+kbQUzJnErE/j7iRMBY2jVtR9d/OLPEH9HXzAo5Z9AoGAfdXP +0eDAe+Vy0/L2DWk4masPgHzFSHGofMpiBplFRiR5N79cPRVrLhdTYj1r6g/YGpHh +pdlpgfn0n4w+0X5UWYffmagEBg2wy4o05oya2Mcwq6oSYoPpSWXzKIriHkkfDkjz +RhHKoh/9mWOldrDl3utNLXTHa7WvVnx+FQrC8VECgYBB4HThlLUU6EvyJKTmFDbt +uNzP9UwuDCENzD9hPJyEX2fdTsGl4KbXnbUujJAN/OWZx4ucC4ecDaHvkKtgsTK/ +pMyDSNiKfisjxpTTsQN/RTl90Zbniyp4AdSvACa+iAqHa1JBQqQud/SKP8cjZ/g9 +jK5NclbGyH0rD3oSjfchrw== +-----END PRIVATE KEY----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.crt b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.crt new file mode 100644 index 0000000000..5a934cfa02 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDqzCCApOgAwIBAgIUCP/0owRzV30Qg5pz85FUSwbkND0wDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgRmlyZU1VRCBJc3N1ZXIgQXV0aG9yaXR5IFRlc3QgQ0Ew +HhcNMjYxMDAyMDMwNDM2WhcNMzYwOTI5MDMwNDM2WjAiMSAwHgYDVQQDDBd3cm9u +Zy1hY2NvdW50LW5hbWVzcGFjZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAPc1Kmjys+Fc9dsgrHILNMSc1v3R6AcDUyS90V18nDztyHxfv+v/d8+1dEju +LZxcghA1F6xcvt5zaH3kN9Q4hxluujUb/I/gAwUfuwbghQDFOw1eawYW+KgFyVH+ +S3JDeQH+ketKzTOiTnhLnRfig77MDiNdHGq29y3+6CZdtPC0F0SZHsrP5tR0QJf0 +YJ0oLOB05GALLT1nPCBtsRXbsOprjBWvt8wkqtzEaA1IH+jfBaXL6YCVsoGvcOLb +9nRdukWN/KjiGP4Vypw3p5WAnqy03zjWw01KPDKafZaQaPmlgjhs6mW3n5ef8yel +qQ2Lo50gREihBYuCYmajmfVMU30CAwEAAaOBzzCBzDBNBgNVHREERjBEhjFzcGlm +ZmU6Ly9maXJlbXVkL25zL290aGVyLXRlc3Qvc2EvYWNjb3VudC1zZXJ2aWNlggls +b2NhbGhvc3SHBH8AAAEwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYD +VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBRRgriSJit+tjZ9 +aV/4mAcPXv0KrzAfBgNVHSMEGDAWgBSxksJwU0ddZ5EJY4JaifyoiOTuRzANBgkq +hkiG9w0BAQsFAAOCAQEAoKXLGTeKkX5TcCpDho3SQMgRjEcy6OQVKR+4pYaFiDup +Mp3vlBzPWdf4BRoKExCw+e5uKuHCjsnCkRqXxYGcIpgBn2TiWQ+fRhJbAXgainwZ +y+SshvWMmJt6F0v22pNZXLenDlg79jGbplUuWgte+BGMdmc+xLbcIN0Pvwq12IZq +rbDlPMN5GiLX1RiGGF7smOP8dyzzdg5U5EAvQFhhyuxRrGu0j5tNRE4amLbmf0W4 +mixWt4BZYEpN2/SyEYrb5iznymIuNxJpfIzYf3gjMEzKBxKGmk109KUrMHpni8IB +fVg6fNwQXEeKPWSEgtZ/bZEpQWJr9K+xrvsLPMIc3w== +-----END CERTIFICATE----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.key b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.key new file mode 100644 index 0000000000..a1b1e85cc8 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-account-namespace.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD3NSpo8rPhXPXb +IKxyCzTEnNb90egHA1MkvdFdfJw87ch8X7/r/3fPtXRI7i2cXIIQNResXL7ec2h9 +5DfUOIcZbro1G/yP4AMFH7sG4IUAxTsNXmsGFvioBclR/ktyQ3kB/pHrSs0zok54 +S50X4oO+zA4jXRxqtvct/ugmXbTwtBdEmR7Kz+bUdECX9GCdKCzgdORgCy09Zzwg +bbEV27Dqa4wVr7fMJKrcxGgNSB/o3wWly+mAlbKBr3Di2/Z0XbpFjfyo4hj+Fcqc +N6eVgJ6stN841sNNSjwymn2WkGj5pYI4bOplt5+Xn/MnpakNi6OdIERIoQWLgmJm +o5n1TFN9AgMBAAECggEABpCyZiQf89nAq8ej3MmAZsJVkVscQudrM1wZLdbr3VBh +VTBDzBQ2Td1fT7qHmpH4YE7QqKKz7Pt6qHFBrFCuAdZnepaaMAX+fonXsTiQP7N9 +PH8n73r3spqovJU40rmJAq0MmgecCIWEePxlGSfKYOxRac4Eva7LRLzy1GYDsqrA +YLhrIZRn2YZ4ipkSNXoqiribhL58HmAMCOa5yC7bJqGkv4vGK34Dx2UR72Jcro78 +75uMYloD5VLPwPg0Vu+Uqbjdf4a0f/SoLcGSt31OeTEyocK1qiQanZEKESpigMUm +WATiuJybtpFfWufUS51lfFMe2ykcFI4fukijBpwh3wKBgQD8fCNZaMP64jyNAbM7 +Xn0pC4T5aXGVu6cuuV+IYtubGPQAZUQfQQxTQZrgTH6Y8MEjoyTH4Q4oW8fhLz0I +ZZXGrpr5GUmObrck91YNqVU1N7As9k8UJhzstkW+LbnLTwWOVZ6gokS5GwOSAnOc +4ljG7GwIdFQyBEnoD2FBdIEIRwKBgQD6pjgqIsuCWZITLnhUmUpN573yj1isok4T +SyUA7Sbdx+/N/wiTk6wfNm6JrAEwWSrTuqhPKRFlCHULgVL9L9Asd3gXujhq/KFU +d2UsCpzRvW6fcHGPHFOpZw37BaMck83mVFIv81mN17eHICriZ7ITOdgrUISJJyUF +bCpAffnsGwKBgQC9ZT17Dzyb0OOM/q59JXcLuAlqsm8y284gHYwNGeMUKBa4yT3d +mATv2zGbeaYpgcfPvMyVZzwgiCCayb2ls9YzcLztiMuFnYWipCqYGuLBBeIRCD7v +pVtjMaOFcnWBjehkCdPxOWgF1r7J4y7oi13+8lBj0ydpUZBDFG5nFEbKdwKBgAbJ +37WMcbSbFnC8jnfEGxYXE7bxGPa8Ap9VJrBqu+W/14fdw26zzjKeN8o0xWd40scf +RBW4yAbTftAL9aJz3BCIP9FsssB7DSeLgEr8Epk/pzJcSkcU/lMVPnSxB2Trv+Tg +HcW8so077XWUcnTlWBZbN7acnKpWTBNkhZRvlQhHAoGADlPE+2FkkdLBf59ypLW/ +FYWno0q0e/GACkR3pvRkqOMVGRk1wfdqN1jn4sCWX6koKP8ZNayiClZzU4OOfc7b +mB6EfZesRTkkUV9k/jp/Fh9uINZzAnmC5WsgOLiCeo6g3dU3QBXhKDsyiFdsG1Ie +5w5m8C0d9EgZijh6G1eBi68= +-----END PRIVATE KEY----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.crt b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.crt new file mode 100644 index 0000000000..63ccea6860 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDqDCCApCgAwIBAgIUBMHwpq+Kfzv5MlhErqvEmvVHN1UwDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgRmlyZU1VRCBJc3N1ZXIgQXV0aG9yaXR5IFRlc3QgQ0Ew +HhcNMjYxMDAyMDI1OTM5WhcNMzYwOTI5MDI1OTM5WjAaMRgwFgYDVQQDDA93cm9u +Zy1uYW1lc3BhY2UwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6boL+ +dgHH5HP44JSeYsEW7Ld9BQsqGvxdTasdKAUa5xDB342XYG6F4JhRKl57Kt25WMXY +a1fOB3mA+wxwEHJPwDNTNk7lKpaPR4d5kVsC0LIusNDPfqxxJayARr791jNHguE1 +3FYEodHWv0j9xbXZvVCH+XHZETE0dhPhpzSDGD0U4E5kwxiSMjT8QcfQPIdGdyFC +yAxhDGRsa3gPaS8uKSBxQig4ehaiA1Rx/n7rEeCjK+f9QkY3GMNnsoYsyPEm6M0M +5bCk8Nktbb4eLswXw331CJsB3DBZF75WbQKR5cJ5DQVaXR9bmUlCSXPfedN1aRl2 +nxYdYQd2tLPPg8QnAgMBAAGjgdQwgdEwUgYDVR0RBEswSYY2c3BpZmZlOi8vZmly +ZW11ZC9ucy9vdGhlci10ZXN0L3NhL2dhbWUtc2Vzc2lvbi1zZXJ2aWNlgglsb2Nh +bGhvc3SHBH8AAAEwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0l +BBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTr6f7mR9kVnXwiqhuI +ER/NA0PcBjAfBgNVHSMEGDAWgBSxksJwU0ddZ5EJY4JaifyoiOTuRzANBgkqhkiG +9w0BAQsFAAOCAQEAm3oMhbiIhcQIw+5gniIIHPq3IQm6Hjk223uEZvCObWtxYhtt +1hrvfLR+gSP4OD1b2ABMylciuFAErkn10dHOg/7d0E5lFQIr5/WKLLVvsTgdfPYH +SdaUDsRYsoGFpuRVRgnqp/rVai64qWN3STK6tMTipNu9ZNGemuz8F3sY+C+Y9mpd +8KNElt3QrZ40DDvO3FlA92Jxoi1qfDMUgXnkXaJTRQWd+FJivAY6y9x9FgSOHRPs +54KSkqbuMv2xF2xZ2tZdmK96S1k1RxFv+jT2F2vbYlo+NaNitkVm++8WPHi3qD0g +PZLH7UDb0nF2orTrsxOmrPUoMMDKO9uogvWymA== +-----END CERTIFICATE----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.key b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.key new file mode 100644 index 0000000000..11d95fd031 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-namespace.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC6boL+dgHH5HP4 +4JSeYsEW7Ld9BQsqGvxdTasdKAUa5xDB342XYG6F4JhRKl57Kt25WMXYa1fOB3mA ++wxwEHJPwDNTNk7lKpaPR4d5kVsC0LIusNDPfqxxJayARr791jNHguE13FYEodHW +v0j9xbXZvVCH+XHZETE0dhPhpzSDGD0U4E5kwxiSMjT8QcfQPIdGdyFCyAxhDGRs +a3gPaS8uKSBxQig4ehaiA1Rx/n7rEeCjK+f9QkY3GMNnsoYsyPEm6M0M5bCk8Nkt +bb4eLswXw331CJsB3DBZF75WbQKR5cJ5DQVaXR9bmUlCSXPfedN1aRl2nxYdYQd2 +tLPPg8QnAgMBAAECggEAQu5XABUMuZ+GlUTHhn9s1BajH3K2meS7UqIGOz75ajmn +lfr04fJga5cBCC6+Ydi3Zon86aBMEy8yy4AV7IuzBne51XeLZpHeIM1s0VPCiWW0 +erfHF59iOHLuldUQT6Bdo6BUy1nx1dLku4TMJzOagHQLm+2NloEqGawEokA9xYxK +rjR+JgdE/a7QJ1KZFUbUvXxeIXEL2ryno9AU24quyGdIb1pAjizbtRKfcx+19sga +9IFgkyqVkK52+IIasB3yLgvCjtRQb4EWDXYnR4igvLH9MvUYuls3qSNNQlijSL4A +Afwr/5Z+4gl2pMBd3UqMhSzNYlODHDL1sEUsN9Qk4QKBgQDRo+K2f6VLFIXGgXFe +wazruRn5kDkEb7rbbi6Ne8CpBPC6TtVclrue08F2W3dQ8SjxHXA4Av7/JeoJhjFl +vuSxxeg78i6ZIyyEMoejmjaMMbvypjCwoxMiG8sQN46Ya7pff8wRJ3RKOBsjmenX +JTvE494m9Aqq9ETuozy9KH5qxwKBgQDjqMA5UncuAZcFSrK5Y23faPIpQssIiFVN +FJbhFRBsUa8Sz4v5atvRt4CzpArhdbC1XutIbv9C9lngTi1fW/WOGrLzQA7mPgk7 +SncSWmhTbOaVRQPi/9Dy/bLMqm7fYap9LebyH5HSePteL0IJuG0jd6Y365qqJoZf +amzScqN7oQKBgHKFPX8Ggexe3KlQ4vaphGYM6vSa5ZrX0lK2gPXHKbrrOPn9wK5g +pUOhV+jpFGgCJaR5uWjPsi79rjjftrJnMpUukKvWo8ACJ/pbhB9KSgwRyyNFyAlm +PDiAyFAmmV4IU3qB3J9uVyeIOMMc/FIMQ/dNp3jODdnPsKxQPgjzSwPXAoGAGbke +hxuPRc5+LuXizdmzN3QXMJxQbpVg9gWmiqYjpemQ25JB4Zu2XLrcOvAFHrZ6kfO4 +qAWKqBlHzHVo4QZ192mC4MNTK6bEykM+sv8uHIcIgsM6jjKTfHE3+7IiNvFFH0HJ +f4AbrOlolZrHXmvNQR2q1VS0tBcIRc2zoA+98yECgYBVgobyfscio7q/H1OWdRw/ +Et9wRp6riu/b2Ga67S9SUozlm5Z4kFUAfloChSrwnN/zf3v5D9xGwTlggD/w7nNd +IG0xY3mnsnEe8kVATdbJS+h/t2D4jnXVbmwXHWTbXeff5Oo3Nh/pjFb3IqODDQjr +dlbzMa6/BCTtZSDKwX/T0A== +-----END PRIVATE KEY----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.crt b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.crt new file mode 100644 index 0000000000..f8eb9b5ab9 --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDnzCCAoegAwIBAgIUFJ417Et3M/QubbjzKwRh3yM7x+swDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgRmlyZU1VRCBJc3N1ZXIgQXV0aG9yaXR5IFRlc3QgQ0Ew +HhcNMjYxMDAyMDI1OTM4WhcNMzYwOTI5MDI1OTM4WjAYMRYwFAYDVQQDDA13cm9u +Zy1zZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwEYT/s7L +1nvhMb2sPEhU5LdevKjyUz0wHIieYw8FNYtakQdfenEviV1hcPFy+J8LcStV/Q8r +BSmOm926JzRLy81LPijy6aUt0IXKZrdeHCGnvRwULQkXqUiZCipjhF1SbUx6Utdm +ZSa4L2rQqE7NWrwgYzh2SrfZEIHtYqxZg64hLgCUu6LT091dudWZL6u3Ytwnhzv6 +oHbgegzarUDbVzkVFFG9DBn/TjyjiQuON9nnVvRjstBct/j7FZRXeVTyt8FgbQZU +r+RO+jI8hZNio6hT0EPZ5++z6lYVW10mqrs/SVPw+OCo2bqDIG3bvxC+4Fwa9srx +vf7ayWsy3GcFwQIDAQABo4HNMIHKMEsGA1UdEQREMEKGL3NwaWZmZTovL2ZpcmVt +dWQvbnMvdGVzdC9zYS9nYW1lLWRlc2lnbi1zZXJ2aWNlgglsb2NhbGhvc3SHBH8A +AAEwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYB +BQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBSfZVbAzcm8o5CjddVmRdbNjYLVLjAf +BgNVHSMEGDAWgBSxksJwU0ddZ5EJY4JaifyoiOTuRzANBgkqhkiG9w0BAQsFAAOC +AQEAryEGyfawzh2EUIQlPpk/dJfWfFTeCKGZd1qSRRYlRR6nFjSwHgr6XBoPafqP +XtO1J0n6fFSuMnx16TG9vjoDI+3QE54EdW6mEk6f2jTFm3Of66PsidJemTq9P9mZ +u2v74t/JHC6hA0CWfWK04aAP0yqhd4jUDFZ0yYWKLrVL/rofnkdNBTgj2QL3yrd+ +1DiWgAe+RLKp6He5Jz+CTrluZ3CdSIWT/DKe9vgpDfplZsBrolMetLRpJ5FGWNUI +etf9qRf6BVXhP2U17w6r0fC+FjvoN3nFaOfGwtn3nr+R50XzZ46H/48ZVljF/ncG +D+d6lUVxj2InYVtZSA+VOC0pyw== +-----END CERTIFICATE----- diff --git a/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.key b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.key new file mode 100644 index 0000000000..4900e6deda --- /dev/null +++ b/services/common-test-support/src/testFixtures/resources/certs/issuer-authority/wrong-service.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDARhP+zsvWe+Ex +vaw8SFTkt168qPJTPTAciJ5jDwU1i1qRB196cS+JXWFw8XL4nwtxK1X9DysFKY6b +3bonNEvLzUs+KPLppS3Qhcpmt14cIae9HBQtCRepSJkKKmOEXVJtTHpS12ZlJrgv +atCoTs1avCBjOHZKt9kQge1irFmDriEuAJS7otPT3V251Zkvq7di3CeHO/qgduB6 +DNqtQNtXORUUUb0MGf9OPKOJC4432edW9GOy0Fy3+PsVlFd5VPK3wWBtBlSv5E76 +MjyFk2KjqFPQQ9nn77PqVhVbXSaquz9JU/D44KjZuoMgbdu/EL7gXBr2yvG9/trJ +azLcZwXBAgMBAAECggEADYHezbvBXiP9wfzNKL78F8U6Bo7n1ykpRBfk6JiZiRVt +G1slPfjNmhzRR5nutcCWkTC2LbzvDMHKnvCIr1BhMsQNUSSXTAqqmUeM3IJtPhSv +L/3U/QTygJX1Cl3H9/iGXd9NiJxROTHrJomedvRyQLmOnOnOhZk8yogWISRydWma +1WNdxQndVwfOULWOUi6o17W44HV0PExnNsx5HO/l2xaCSdgBxxIQaR/PaK2B7y25 +FLM/Y8zke06VK2Yo5ElIgHPKDtAJTI68KWJghCYNDJsOm2F85av3T5B0llS/mW1v +F3zj1urQeQs5rwKc8JVfAFpyuTszSw3+lHUystWosQKBgQD4CTMtB6df++2hA/RY +HtawBdL9fzO4Hf6raVo5Wie8QlzMFO65/ZPow98IO+BGftkW64GSwaKgdRR6IVu/ +v36hYeDOkkSHKFAk1pDvzzzEPyowsaOzxl5SpopxTMpMfRL7L8fu4iY6enHelXln +qYFMU16pB1LmMUqn2AuLt7gWgwKBgQDGcoaAXl9oOmcZbdMS0WOmtBR5iOdNwWCo +iwsoB6SklkkxLfdiTUDyHAkPJxXIdoUjBgJE35eW4mqX+Zio8DU+x0r3k3e7ex8i +WRdL55Jhv3RlCppZxzgjA8C77D9W1RQbypcqlD7NWfZreuyr9IOuuroaxDagOFY/ +tOOXkolfawKBgQDdaDDzgEKLLrJXKdWCl7yikgBeYp7DOpsrXba5PV388ewuDH1x +LwdKHxZHHlO7+d1FVWJro0fNHdXykzZ4OrMJ0fo/y1c6ouSvjY0BVCd1MsExiFCN +2IQ4GQu5yYdHsdowuN0qw1rGlqhwvVMLEsclX8I+9hes/dEbdIIR7SR5iwKBgEb2 +9Xo6RUv0dqH1UCHOlyAqDZhYiL6ZhINBFcA+23Wv+ISJt4mDrtHljKfKhlOlbn7T +y0Pt4TunxA6MxzbCj4ffpMNcDNkSclPKIDaYnRQvbuQjIocwYrbCxM1u8keO8x3t +GJm1Ya/1l9Vfo/rp+Z0mUR75Q7+P5efqO+kcEdv5AoGAbRIVHdUsPrjSDyPZPpz1 +6xCj9VCW1bRop7A7aQ8tEyWmKGDte7lNxJ6rks4oUSVrhaPbEFvkjV3I9lG2nbcg +ZF+EVfxSU0zh7EKPD6AcvrdDzgdiGb1Ffmye35WbY3nFucrSGvRKhAg5rwaQYFcW +k95PdOdwWxVvjSAL4ptNDqk= +-----END PRIVATE KEY----- diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index bf0c7c7612..81a8bd7842 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -79,6 +79,7 @@ dependencies { testImplementation(libs.grpc.inprocess) testImplementation(testFixtures(project(":game-session-service"))) testImplementation(project(":game-logic-service")) + add("crossServiceTestImplementation", project(":account-service")) } tasks.named("bootRun") { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java new file mode 100644 index 0000000000..d00684e8cb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java @@ -0,0 +1,434 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Unwired Game Session client for authenticated Account issuer-source readback only. */ +public final class AccountIssuerAuthorityClient + extends AbstractReloadingBlockingGrpcClient< + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final String READBACK_SCHEMA_VERSION = "account-auth-issuer-source-readback/v1"; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + + private final String workloadNamespace; + private final String expectedIssuerId; + + /** + * Creates a source-only client. Construction does not initialize a channel or enable the RPC. The + * supplied customizer is the existing Game Session internal-RPC middleware seam. + */ + public AccountIssuerAuthorityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, + String expectedIssuerId) { + super( + endpoints, + requireGameSessionMtls(tlsProps), + channelFactory, + stubCustomizer, + AccountIssuerAuthorityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + if (expectedIssuerId == null || expectedIssuerId.isBlank()) { + throw new IllegalArgumentException("Exact Account issuer identity is required"); + } + if (stubCustomizer == null) { + throw new IllegalArgumentException("Game Session internal gRPC stub customizer is required"); + } + this.workloadNamespace = workloadNamespace; + this.expectedIssuerId = expectedIssuerId; + } + + /** Initializes this client only when an explicit owner activates the source handoff. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub buildStub( + ManagedChannel channel) { + return applyStubCustomizer( + IssuerAuthorityServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) + .withCompression("gzip")); + } + + /** Reads Account's current issuer checkpoint without selecting an individual event. */ + public SourceReadback readCurrent(String canonicalRequestId) { + UUID requestId = parseCanonicalNonNilUuid(canonicalRequestId, "request ID"); + return read(requestId, null); + } + + /** Reads one exact historical event alongside Account's current issuer checkpoint. */ + public SourceReadback readCommittedEvent( + String canonicalRequestId, String canonicalPositiveOutboxSequence) { + UUID requestId = parseCanonicalNonNilUuid(canonicalRequestId, "request ID"); + BigInteger requestedSequence = + parseCanonicalPositiveDecimal(canonicalPositiveOutboxSequence, "requested outbox sequence"); + return read(requestId, requestedSequence); + } + + private SourceReadback read(UUID requestId, BigInteger requestedSequence) { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Account issuer authority client is not initialized"); + } + + ReadIssuerAuthorityForRuntimeRequest.Builder request = + ReadIssuerAuthorityForRuntimeRequest.newBuilder() + .setIssuerId(expectedIssuerId) + .setRequestId(requestId.toString()); + if (requestedSequence != null) { + request.setRequestedOutboxSequence(requestedSequence.toString()); + } + ReadIssuerAuthorityForRuntimeResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readIssuerAuthorityForRuntime(request.build()); + return verifyResponse(response, requestId, requestedSequence); + } + + private SourceReadback verifyResponse( + ReadIssuerAuthorityForRuntimeResponse response, + UUID requestId, + BigInteger requestedSequence) { + if (response == null) { + throw invalidResponse("response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("response contains unsupported fields"); + } + if (!response.hasSourceSnapshot()) { + throw invalidResponse("response has no source snapshot"); + } + if (response.hasRequestedEventCanonicalJson() != (requestedSequence != null)) { + throw invalidResponse("requested-event presence does not match the exact selector"); + } + if (!READBACK_SCHEMA_VERSION.equals(response.getSchemaVersion()) + || !workloadNamespace.equals(response.getTargetNamespace()) + || !requestId.toString().equals(response.getRequestId())) { + throw invalidResponse("response schema, namespace, or request echo changed"); + } + + IssuerAuthoritySourceSnapshot wireSnapshot = response.getSourceSnapshot(); + if (!wireSnapshot.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("source snapshot contains unsupported fields"); + } + if (!expectedIssuerId.equals(wireSnapshot.getIssuerId())) { + throw invalidResponse("source snapshot issuer identity changed"); + } + + String sourceScope = "issuer/" + expectedIssuerId; + String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + if (!sourceScope.equals(wireSnapshot.getSourceScope()) + || !streamKey.equals(wireSnapshot.getOutboxStreamKey())) { + throw invalidResponse("source snapshot scope or stream changed"); + } + + BigInteger generation = + parseResponsePositiveDecimal( + wireSnapshot.getIssuerAuthGeneration(), "issuer auth generation"); + BigInteger sourceVersion = + parseResponsePositiveDecimal(wireSnapshot.getSourceVersion(), "source version"); + BigInteger currentSequence = + parseNonnegativeDecimal(wireSnapshot.getOutboxSequence(), "outbox sequence"); + IssuerGenerationAuthorityEvent latestEvent = null; + if (currentSequence.signum() == 0) { + if (!BigInteger.ONE.equals(generation) + || !BigInteger.ONE.equals(sourceVersion) + || wireSnapshot.hasLatestEventCanonicalJson()) { + throw invalidResponse("zero checkpoint is not the proved positive source baseline"); + } + } else { + if (!wireSnapshot.hasLatestEventCanonicalJson()) { + throw invalidResponse("positive checkpoint has no complete latest event"); + } + latestEvent = + verifyEvent( + wireSnapshot.getLatestEventCanonicalJson(), + "latest source event", + expectedIssuerId, + sourceScope, + streamKey); + if (!currentSequence.equals( + parseResponsePositiveDecimal(latestEvent.outboxSequence(), "event sequence")) + || !generation.equals( + parseResponsePositiveDecimal(latestEvent.issuerAuthGeneration(), "event generation")) + || !sourceVersion.equals( + parseResponsePositiveDecimal(latestEvent.sourceVersion(), "event source version"))) { + throw invalidResponse("latest event does not match the complete source checkpoint"); + } + } + + IssuerGenerationAuthorityEvent requestedEvent = null; + if (requestedSequence != null) { + if (!response.hasRequestedEventCanonicalJson()) { + throw invalidResponse("historical selection has no requested event"); + } + requestedEvent = + verifyEvent( + response.getRequestedEventCanonicalJson(), + "requested historical event", + expectedIssuerId, + sourceScope, + streamKey); + BigInteger selectedEventSequence = + parseResponsePositiveDecimal(requestedEvent.outboxSequence(), "requested event sequence"); + BigInteger selectedGeneration = + parseResponsePositiveDecimal( + requestedEvent.issuerAuthGeneration(), "requested event generation"); + BigInteger selectedVersion = + parseResponsePositiveDecimal( + requestedEvent.sourceVersion(), "requested event source version"); + if (!requestedSequence.equals(selectedEventSequence) + || selectedEventSequence.compareTo(currentSequence) > 0 + || selectedGeneration.compareTo(generation) > 0 + || selectedVersion.compareTo(sourceVersion) > 0) { + throw invalidResponse( + "requested historical event is not exact or is ahead of the snapshot"); + } + if (selectedEventSequence.equals(currentSequence) + && (latestEvent == null + || !requestedEvent.canonicalJson().equals(latestEvent.canonicalJson()))) { + throw invalidResponse("current-sequence historical event differs from the latest event"); + } + } + + SourceSnapshot snapshot = + new SourceSnapshot( + expectedIssuerId, + sourceScope, + streamKey, + generation.toString(), + sourceVersion.toString(), + currentSequence.toString(), + latestEvent); + return new SourceReadback(requestId.toString(), workloadNamespace, snapshot, requestedEvent); + } + + private static IssuerGenerationAuthorityEvent verifyEvent( + String wireJson, + String label, + String expectedIssuer, + String expectedScope, + String expectedStream) { + try { + IssuerGenerationAuthorityEvent event = IssuerGenerationAuthorityEventV1Codec.verify(wireJson); + if (!wireJson.equals(event.canonicalJson())) { + throw new IllegalArgumentException("event JSON is not exact canonical JSON"); + } + UUID eventRequestId = parseCanonicalNonNilUuid(event.requestId(), label + " request ID"); + if (!event.issuerId().equals(expectedIssuer) + || !event.sourceScope().equals(expectedScope) + || !event.outboxStreamKey().equals(expectedStream) + || !event.eventId().equals(EVENT_ID_PREFIX + eventRequestId)) { + throw new IllegalArgumentException("event identity or source binding changed"); + } + return event; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException(label + " is invalid", exception); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + final UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } + + private static BigInteger parseCanonicalPositiveDecimal(String value, String label) { + BigInteger parsed = parsePositiveDecimal(value, label); + return parsed; + } + + private static BigInteger parsePositiveDecimal(String value, String label) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical positive decimal string"); + } + return new BigInteger(value); + } + + private static BigInteger parseResponsePositiveDecimal(String value, String label) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw invalidResponse(label + " must be a canonical positive decimal string"); + } + return new BigInteger(value); + } + + private static BigInteger parseNonnegativeDecimal(String value, String label) { + if (value == null || !value.matches("(?:0|[1-9][0-9]*)")) { + throw invalidResponse(label + " must be a canonical zero-or-positive decimal string"); + } + return new BigInteger(value); + } + + private static IllegalStateException invalidResponse(String message) { + return new IllegalStateException("Account issuer authority response " + message); + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Issuer source readback requires Game Session workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Issuer source readback requires Game Session certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Issuer source readback requires file-backed Game Session workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + /** + * Immutable Account snapshot fields created only after the authenticated response is verified. + */ + public static final class SourceSnapshot { + private final String issuerId; + private final String sourceScope; + private final String outboxStreamKey; + private final String issuerAuthGeneration; + private final String sourceVersion; + private final String outboxSequence; + private final IssuerGenerationAuthorityEvent latestEvent; + + private SourceSnapshot( + String issuerId, + String sourceScope, + String outboxStreamKey, + String issuerAuthGeneration, + String sourceVersion, + String outboxSequence, + IssuerGenerationAuthorityEvent latestEvent) { + this.issuerId = issuerId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.issuerAuthGeneration = issuerAuthGeneration; + this.sourceVersion = sourceVersion; + this.outboxSequence = outboxSequence; + this.latestEvent = latestEvent; + } + + public String issuerId() { + return issuerId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String issuerAuthGeneration() { + return issuerAuthGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public String outboxSequence() { + return outboxSequence; + } + + public Optional latestEvent() { + return Optional.ofNullable(latestEvent); + } + } + + /** Immutable result for current or historical source readback, minted only after verification. */ + public static final class SourceReadback { + private final String requestId; + private final String targetNamespace; + private final SourceSnapshot sourceSnapshot; + private final IssuerGenerationAuthorityEvent requestedEvent; + + private SourceReadback( + String requestId, + String targetNamespace, + SourceSnapshot sourceSnapshot, + IssuerGenerationAuthorityEvent requestedEvent) { + this.requestId = requestId; + this.targetNamespace = targetNamespace; + this.sourceSnapshot = sourceSnapshot; + this.requestedEvent = requestedEvent; + } + + public String requestId() { + return requestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public SourceSnapshot sourceSnapshot() { + return sourceSnapshot; + } + + public Optional requestedEvent() { + return Optional.ofNullable(requestedEvent); + } + } +} diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java new file mode 100644 index 0000000000..f9d61b69f8 --- /dev/null +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java @@ -0,0 +1,263 @@ +package crossservice.net.firedevops.firemud.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import 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.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityGrpcService; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Physical mutual-TLS proof for the deliberately unwired issuer-source readback handoff. */ +class AccountIssuerAuthorityGrpcMtlsCrossServiceTest { + @TempDir private Path tempDir; + + private final Map copiedCertificates = new HashMap<>(); + + private static final String NAMESPACE = "test"; + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String SOURCE_SCOPE = "issuer/" + ISSUER_ID; + private static final String STREAM_KEY = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + SOURCE_SCOPE; + private static final String CURRENT_EVENT_REQUEST_ID = "11111111-1111-4111-8111-111111111111"; + private static final String HISTORICAL_EVENT_REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String CURRENT_READ_REQUEST_ID = "33333333-3333-4333-8333-333333333333"; + private static final String HISTORICAL_READ_REQUEST_ID = "44444444-4444-4444-8444-444444444444"; + + @Test + void exactWorkloadIdentitiesCarryCurrentAndHistoricalReadbacksOverSocketMtls() throws Exception { + AccountIssuerAuthorityEventProducer producer = producerWithPositiveReadbacks(); + Server server = startServer("account", producer); + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + AccountIssuerAuthorityClient.SourceReadback current = + client.readCurrent(CURRENT_READ_REQUEST_ID); + AccountIssuerAuthorityClient.SourceReadback historical = + client.readCommittedEvent(HISTORICAL_READ_REQUEST_ID, "1"); + + assertThat(current.requestId()).isEqualTo(CURRENT_READ_REQUEST_ID); + assertThat(current.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(current.sourceSnapshot().outboxSequence()).isEqualTo("2"); + assertThat(current.sourceSnapshot().latestEvent().orElseThrow().canonicalJson()) + .isEqualTo(event(CURRENT_EVENT_REQUEST_ID, 2L, 3L, 3L).canonicalJson()); + assertThat(current.requestedEvent()).isEmpty(); + assertThat(historical.sourceSnapshot().outboxSequence()).isEqualTo("2"); + assertThat(historical.sourceSnapshot().latestEvent().orElseThrow().canonicalJson()) + .isEqualTo(event(CURRENT_EVENT_REQUEST_ID, 2L, 3L, 3L).canonicalJson()); + assertThat(historical.requestedEvent().orElseThrow().canonicalJson()) + .isEqualTo(event(HISTORICAL_EVENT_REQUEST_ID, 1L, 2L, 2L).canonicalJson()); + + verify(producer).readCurrent(ISSUER_ID); + verify(producer).readCommittedEvent(ISSUER_ID, 1L); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void trustedButWrongGameSessionPeerIsDeniedBeforeProducerAccess(String clientIdentity) + throws Exception { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + Server server = startServer("account", producer); + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), clientIdentity)) { + client.init(); + + assertThatThrownBy(() -> client.readCurrent(CURRENT_READ_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + verifyNoInteractions(producer); + } finally { + stop(server); + } + } + + @Test + void missingClientCertificateFailsTheRequiredTlsHandshakeBeforeProducerAccess() throws Exception { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + Server server = startServer("account", producer); + var channel = + NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext( + GrpcSslContexts.forClient().trustManager(certificate("ca.crt").toFile()).build()) + .build(); + try { + assertThatThrownBy( + () -> + IssuerAuthorityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readIssuerAuthorityForRuntime(validRequest())) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + verifyNoInteractions(producer); + } finally { + channel.shutdownNow(); + channel.awaitTermination(2, TimeUnit.SECONDS); + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"game-session", "wrong-account-namespace"}) + void trustedAccountServerWithWrongServiceOrNamespaceIsRejectedBeforeResponseAcceptance( + String serverIdentity) throws Exception { + AccountIssuerAuthorityEventProducer producer = producerWithPositiveReadbacks(); + Server server = startServer(serverIdentity, producer); + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + assertThatThrownBy(() -> client.readCurrent(CURRENT_READ_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + verify(producer).readCurrent(ISSUER_ID); + } finally { + stop(server); + } + } + + private static AccountIssuerAuthorityEventProducer producerWithPositiveReadbacks() { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + IssuerGenerationAuthorityEvent latest = event(CURRENT_EVENT_REQUEST_ID, 2L, 3L, 3L); + IssuerGenerationAuthorityEvent selected = event(HISTORICAL_EVENT_REQUEST_ID, 1L, 2L, 2L); + IssuerAuthoritySnapshot current = + new IssuerAuthoritySnapshot(ISSUER_ID, 3L, 3L, STREAM_KEY, 2L, Optional.of(latest)); + when(producer.readCurrent(ISSUER_ID)).thenReturn(current); + when(producer.readCommittedEvent(ISSUER_ID, 1L)) + .thenReturn(new IssuerAuthorityEventReadback(current, selected)); + return producer; + } + + private AccountIssuerAuthorityClient newClient(int port, String clientIdentity) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate(clientIdentity + ".crt").toString()); + tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); + tls.setCaCert(certificate("ca.crt").toString()); + return new AccountIssuerAuthorityClient( + endpoints, + tls, + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + ISSUER_ID); + } + + private Server startServer(String serverIdentity, AccountIssuerAuthorityEventProducer producer) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + certificate(serverIdentity + ".crt").toFile(), + certificate(serverIdentity + ".key").toFile()) + .trustManager(certificate("ca.crt").toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountIssuerAuthorityGrpcService(producer, NAMESPACE), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private Path certificate(String name) throws IOException { + Path existing = copiedCertificates.get(name); + if (existing != null) { + return existing; + } + + String resourcePath = "/certs/issuer-authority/" + name; + try (InputStream resource = + AccountIssuerAuthorityGrpcMtlsCrossServiceTest.class.getResourceAsStream(resourcePath)) { + if (resource == null) { + throw new IllegalStateException("Missing issuer-authority TLS fixture: " + resourcePath); + } + Path copied = tempDir.resolve(name); + Files.copy(resource, copied); + copiedCertificates.put(name, copied); + return copied; + } + } + + private static IssuerGenerationAuthorityEvent event( + String requestId, long sequence, long generation, long sourceVersion) { + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + requestId, + "requestId", + requestId, + "issuerId", + ISSUER_ID, + "sourceScope", + SOURCE_SCOPE, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private static net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest + validRequest() { + return net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setRequestId(CURRENT_READ_REQUEST_ID) + .build(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + server.awaitTermination(2, TimeUnit.SECONDS); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java new file mode 100644 index 0000000000..a884e3c860 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java @@ -0,0 +1,630 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.ClientCall; +import io.grpc.Grpc; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class AccountIssuerAuthorityClientTest { + private static final String NAMESPACE = "test"; + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String SOURCE_SCOPE = "issuer/" + ISSUER_ID; + private static final String STREAM_KEY = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + SOURCE_SCOPE; + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID EVENT_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String LARGE_COUNTER = "922337203685477580812345678901234567890"; + + @Test + void currentReadVerifiesAndReturnsTheSequenceZeroPositiveBaseline() throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.readIssuerAuthorityForRuntime(any())).thenReturn(baselineResponse()); + AccountIssuerAuthorityClient client = newClient(stub); + + AccountIssuerAuthorityClient.SourceReadback readback = + client.readCurrent(REQUEST_ID.toString()); + + assertThat(readback.requestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(readback.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(readback.sourceSnapshot().issuerId()).isEqualTo(ISSUER_ID); + assertThat(readback.sourceSnapshot().sourceScope()).isEqualTo(SOURCE_SCOPE); + assertThat(readback.sourceSnapshot().outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(readback.sourceSnapshot().issuerAuthGeneration()).isEqualTo("1"); + assertThat(readback.sourceSnapshot().sourceVersion()).isEqualTo("1"); + assertThat(readback.sourceSnapshot().outboxSequence()).isEqualTo("0"); + assertThat(readback.sourceSnapshot().latestEvent()).isEmpty(); + assertThat(readback.requestedEvent()).isEmpty(); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ReadIssuerAuthorityForRuntimeRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).readIssuerAuthorityForRuntime(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(requestCaptor.getValue().getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(requestCaptor.getValue().hasRequestedOutboxSequence()).isFalse(); + } + + @Test + void currentReadVerifiesPositiveLatestEventAndArbitraryPrecisionCounters() throws Exception { + String sequence = LARGE_COUNTER; + IssuerGenerationAuthorityEvent event = + event(sequence, LARGE_COUNTER, LARGE_COUNTER, EVENT_REQUEST_ID); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.readIssuerAuthorityForRuntime(any())) + .thenReturn( + snapshotResponse(LARGE_COUNTER, LARGE_COUNTER, sequence, event.canonicalJson())); + AccountIssuerAuthorityClient client = newClient(stub); + + AccountIssuerAuthorityClient.SourceReadback readback = + client.readCurrent(REQUEST_ID.toString()); + + assertThat(readback.sourceSnapshot().issuerAuthGeneration()).isEqualTo(LARGE_COUNTER); + assertThat(readback.sourceSnapshot().sourceVersion()).isEqualTo(LARGE_COUNTER); + assertThat(readback.sourceSnapshot().outboxSequence()).isEqualTo(sequence); + assertLatestEvent(readback.sourceSnapshot().latestEvent().orElseThrow(), event); + } + + @Test + void historicalReadPreservesLargeSelectorAndReturnsSeparateCurrentAndSelectedEvents() + throws Exception { + String currentSequence = "100000000000000000000000000000000000000"; + String selectedSequence = "99999999999999999999999999999999999999"; + IssuerGenerationAuthorityEvent latest = event(currentSequence, "101", "201", EVENT_REQUEST_ID); + IssuerGenerationAuthorityEvent selected = + event( + selectedSequence, + "100", + "200", + UUID.fromString("33333333-3333-4333-8333-333333333333")); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.readIssuerAuthorityForRuntime(any())) + .thenReturn( + snapshotResponse( + "101", "201", currentSequence, latest.canonicalJson(), selected.canonicalJson())); + AccountIssuerAuthorityClient client = newClient(stub); + + AccountIssuerAuthorityClient.SourceReadback readback = + client.readCommittedEvent(REQUEST_ID.toString(), selectedSequence); + + assertLatestEvent(readback.sourceSnapshot().latestEvent().orElseThrow(), latest); + assertLatestEvent(readback.requestedEvent().orElseThrow(), selected); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ReadIssuerAuthorityForRuntimeRequest.class); + verify(stub).readIssuerAuthorityForRuntime(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getRequestedOutboxSequence()).isEqualTo(selectedSequence); + } + + @Test + void historicalReadAtCurrentSequenceRequiresTheCompleteLatestEvent() throws Exception { + IssuerGenerationAuthorityEvent event = event("2", "3", "3", EVENT_REQUEST_ID); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.readIssuerAuthorityForRuntime(any())) + .thenReturn(snapshotResponse("3", "3", "2", event.canonicalJson(), event.canonicalJson())); + AccountIssuerAuthorityClient client = newClient(stub); + + AccountIssuerAuthorityClient.SourceReadback readback = + client.readCommittedEvent(REQUEST_ID.toString(), "2"); + + assertLatestEvent(readback.sourceSnapshot().latestEvent().orElseThrow(), event); + assertLatestEvent(readback.requestedEvent().orElseThrow(), event); + } + + @Test + void rejectsMalformedRequestIdentityOrNoncanonicalHistoricalSelectorBeforeStubUse() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountIssuerAuthorityClient client = newClientWithoutStub(channelFactory); + + for (String invalid : + List.of( + "", + "11111111-1111-4111-8111-11111111111", + "11111111-1111-4111-8111-11111111111x", + "00000000-0000-0000-0000-000000000000")) { + assertThatThrownBy(() -> client.readCurrent(invalid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.readCommittedEvent(invalid, "1")) + .isInstanceOf(IllegalArgumentException.class); + } + for (String invalid : List.of("", "0", "00", "01", "+1", "-1", "1.0", " 1")) { + assertThatThrownBy(() -> client.readCommittedEvent(REQUEST_ID.toString(), invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsEveryResponseEchoAndTopLevelPresenceDeviation() throws Exception { + ReadIssuerAuthorityForRuntimeResponse valid = baselineResponse(); + assertCurrentRejected(null); + assertCurrentRejected(valid.toBuilder().setSchemaVersion("other").build()); + assertCurrentRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertCurrentRejected( + valid.toBuilder().setRequestId("33333333-3333-4333-8333-333333333333").build()); + assertCurrentRejected(valid.toBuilder().clearSourceSnapshot().build()); + assertCurrentRejected(valid.toBuilder().setRequestedEventCanonicalJson("").build()); + assertCurrentRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + } + + @Test + void rejectsEverySourceSnapshotEchoCounterPresenceAndNestedUnknownDeviation() throws Exception { + IssuerAuthoritySourceSnapshot valid = baselineResponse().getSourceSnapshot(); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setIssuerId("other").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setSourceScope("issuer/other").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setOutboxStreamKey("other").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setIssuerAuthGeneration("2").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setSourceVersion("2").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setOutboxSequence("1").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setIssuerAuthGeneration("01").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setIssuerAuthGeneration("+1").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setSourceVersion("").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setOutboxSequence("00").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setOutboxSequence("-1").build())); + assertCurrentRejected(snapshotOnly(valid.toBuilder().setLatestEventCanonicalJson("").build())); + assertCurrentRejected( + snapshotOnly( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())); + } + + @Test + void zeroCheckpointRequiresOnlyTheExactPositiveBaselineAndNoLatestEvent() throws Exception { + assertCurrentRejected(snapshotResponse("0", "1", "0", null)); + assertCurrentRejected(snapshotResponse("1", "0", "0", null)); + assertCurrentRejected(snapshotResponse("2", "1", "0", null)); + } + + @Test + void positiveCheckpointRequiresLatestEventMatchingEveryCurrentField() throws Exception { + assertCurrentRejected(snapshotResponse("2", "2", "1", null)); + IssuerGenerationAuthorityEvent good = event("1", "2", "2", EVENT_REQUEST_ID); + assertCurrentRejected(snapshotResponse("3", "2", "1", good.canonicalJson())); + assertCurrentRejected(snapshotResponse("2", "3", "1", good.canonicalJson())); + assertCurrentRejected(snapshotResponse("2", "2", "2", good.canonicalJson())); + + IssuerGenerationAuthorityEvent mismatchedIssuer = + event("1", "2", "2", EVENT_REQUEST_ID, "another-issuer"); + assertCurrentRejected(snapshotResponse("2", "2", "1", mismatchedIssuer.canonicalJson())); + IssuerGenerationAuthorityEvent malformedIdentity = + event("1", "2", "2", EVENT_REQUEST_ID, ISSUER_ID, "unexpected-event-id"); + assertCurrentRejected(snapshotResponse("2", "2", "1", malformedIdentity.canonicalJson())); + } + + @Test + void rejectsMalformedNoncanonicalOrDigestModifiedEventJson() throws Exception { + IssuerGenerationAuthorityEvent valid = event("1", "2", "2", EVENT_REQUEST_ID); + assertCurrentRejected(snapshotResponse("2", "2", "1", "not-json")); + assertCurrentRejected(snapshotResponse("2", "2", "1", valid.canonicalJson() + " ")); + assertCurrentRejected( + snapshotResponse( + "2", + "2", + "1", + valid + .canonicalJson() + .replace("\"issuerAuthGeneration\":\"2\"", "\"issuerAuthGeneration\":\"3\""))); + assertCurrentRejected( + snapshotResponse( + "2", + "2", + "1", + valid + .canonicalJson() + .replace( + "\"eventDigest\":\"sha256:", "\"unexpected\":true,\"eventDigest\":\"sha256:"))); + } + + @Test + void rejectsHistoricalAbsenceMismatchAheadEvidenceAndNonexactCurrentEvent() throws Exception { + IssuerGenerationAuthorityEvent latest = event("2", "3", "3", EVENT_REQUEST_ID); + ReadIssuerAuthorityForRuntimeResponse current = + snapshotResponse("3", "3", "2", latest.canonicalJson()); + assertHistoricalRejected(current, "1"); + assertHistoricalRejected(snapshotResponse("3", "3", "2", latest.canonicalJson(), ""), "1"); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), latest.canonicalJson()), "1"); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), latest.canonicalJson()), "3"); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), latest.canonicalJson()), + LARGE_COUNTER); + + IssuerGenerationAuthorityEvent aheadSequence = event("3", "3", "3", EVENT_REQUEST_ID); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), aheadSequence.canonicalJson()), + "3"); + IssuerGenerationAuthorityEvent aheadGeneration = event("1", "4", "3", EVENT_REQUEST_ID); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), aheadGeneration.canonicalJson()), + "1"); + IssuerGenerationAuthorityEvent aheadVersion = event("1", "3", "4", EVENT_REQUEST_ID); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), aheadVersion.canonicalJson()), "1"); + IssuerGenerationAuthorityEvent sameSequenceDifferentEvent = + event("2", "3", "3", UUID.fromString("44444444-4444-4444-8444-444444444444")); + assertHistoricalRejected( + snapshotResponse( + "3", "3", "2", latest.canonicalJson(), sameSequenceDifferentEvent.canonicalJson()), + "2"); + IssuerGenerationAuthorityEvent wrongIssuer = + event("1", "2", "2", EVENT_REQUEST_ID, "another-issuer"); + assertHistoricalRejected( + snapshotResponse("3", "3", "2", latest.canonicalJson(), wrongIssuer.canonicalJson()), "1"); + } + + @Test + void unavailableStatusPropagatesOnceWithoutRetryOrFallback() throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Account unavailable")); + when(stub.readIssuerAuthorityForRuntime(any())).thenThrow(unavailable); + AccountIssuerAuthorityClient client = newClient(stub); + + assertThatThrownBy(() -> client.readCurrent(REQUEST_ID.toString())).isSameAs(unavailable); + + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).readIssuerAuthorityForRuntime(any()); + verify(stub, never()).withDeadlineAfter(10L, TimeUnit.SECONDS); + } + + @Test + void constructorRequiresFileBackedMtlsNamespaceIssuerAndMiddleware() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + plaintext, + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + ISSUER_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + BlockingGrpcStubCustomizer.noop(), + "Invalid_Namespace", + ISSUER_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + " ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + null, + NAMESPACE, + ISSUER_ID)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(channelFactory); + } + + @Test + void explicitInitUsesConfiguredAccountTargetAndFileBackedTls(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + CommonGrpcClientProperties tls = mtlsProperties(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + endpoints, + tls, + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + ISSUER_ID); + try { + verifyNoInteractions(channelFactory); + client.init(); + verify(channelFactory) + .buildChannel( + eq("account.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + @Test + void installedPeerInterceptorDeniesMissingAndWrongServerCertificateIdentity() throws Exception { + // These mocked transport attributes exercise the installed guard, not physical mTLS proof. + AccountIssuerAuthorityClient client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + for (SSLSession session : new SSLSession[] {null, peerSession("game-design-service")}) { + ManagedChannel channel = mock(ManagedChannel.class); + Attributes attributes = + session == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + when(channel.newCall(any(), any())).thenAnswer(invocation -> immediateCloseCall(attributes)); + var stub = client.buildStub(channel); + + assertThatThrownBy( + () -> + stub.readIssuerAuthorityForRuntime( + ReadIssuerAuthorityForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setRequestId(REQUEST_ID.toString()) + .build())) + .isInstanceOf(StatusRuntimeException.class) + .extracting(exception -> ((StatusRuntimeException) exception).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + } + } + + private static void assertCurrentRejected(ReadIssuerAuthorityForRuntimeResponse response) + throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.readIssuerAuthorityForRuntime(any())).thenReturn(response); + AccountIssuerAuthorityClient client = newClient(stub); + assertThatThrownBy(() -> client.readCurrent(REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class); + } + + private static void assertHistoricalRejected( + ReadIssuerAuthorityForRuntimeResponse response, String selectedSequence) throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.readIssuerAuthorityForRuntime(any())).thenReturn(response); + AccountIssuerAuthorityClient client = newClient(stub); + assertThatThrownBy(() -> client.readCommittedEvent(REQUEST_ID.toString(), selectedSequence)) + .isInstanceOf(IllegalStateException.class); + } + + private static AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub) throws Exception { + AccountIssuerAuthorityClient client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static AccountIssuerAuthorityClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + ISSUER_ID); + } + + private static IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub mockStub() { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ReadIssuerAuthorityForRuntimeResponse baselineResponse() { + return snapshotResponse("1", "1", "0", null); + } + + private static ReadIssuerAuthorityForRuntimeResponse snapshotOnly( + IssuerAuthoritySourceSnapshot snapshot) { + return envelope().setSourceSnapshot(snapshot).build(); + } + + private static ReadIssuerAuthorityForRuntimeResponse snapshotResponse( + String generation, String sourceVersion, String sequence, String latestEvent) { + return snapshotResponse(generation, sourceVersion, sequence, latestEvent, null); + } + + private static ReadIssuerAuthorityForRuntimeResponse snapshotResponse( + String generation, + String sourceVersion, + String sequence, + String latestEvent, + String requestedEvent) { + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(ISSUER_ID) + .setSourceScope(SOURCE_SCOPE) + .setOutboxStreamKey(STREAM_KEY) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latestEvent != null) { + snapshot.setLatestEventCanonicalJson(latestEvent); + } + ReadIssuerAuthorityForRuntimeResponse.Builder response = + envelope().setSourceSnapshot(snapshot.build()); + if (requestedEvent != null) { + response.setRequestedEventCanonicalJson(requestedEvent); + } + return response.build(); + } + + private static ReadIssuerAuthorityForRuntimeResponse.Builder envelope() { + return ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_ID.toString()); + } + + private static IssuerGenerationAuthorityEvent event( + String sequence, String generation, String sourceVersion, UUID eventRequestId) { + return event(sequence, generation, sourceVersion, eventRequestId, ISSUER_ID); + } + + private static IssuerGenerationAuthorityEvent event( + String sequence, + String generation, + String sourceVersion, + UUID eventRequestId, + String issuerId) { + return event( + sequence, + generation, + sourceVersion, + eventRequestId, + issuerId, + "account-issuer-authority-event-v1:" + eventRequestId); + } + + private static IssuerGenerationAuthorityEvent event( + String sequence, + String generation, + String sourceVersion, + UUID eventRequestId, + String issuerId, + String eventId) { + String scope = "issuer/" + issuerId; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", eventId, + "requestId", eventRequestId.toString(), + "issuerId", issuerId, + "sourceScope", scope, + "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, + "outboxSequence", sequence, + "issuerAuthGeneration", generation, + "sourceVersion", sourceVersion)); + } + + private static ClientCall immediateCloseCall(Attributes attributes) { + return new ClientCall<>() { + private Listener listener; + + @Override + public void start(Listener callListener, Metadata headers) { + listener = callListener; + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(String message, Throwable cause) {} + + @Override + public void halfClose() { + listener.onClose(Status.OK, new Metadata()); + } + + @Override + public void sendMessage(Object message) {} + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setMessageCompression(boolean enabled) {} + + @Override + public Attributes getAttributes() { + return attributes; + } + }; + } + + private static void assertLatestEvent( + IssuerGenerationAuthorityEvent actual, IssuerGenerationAuthorityEvent expected) { + assertThat(actual.canonicalJson()).isEqualTo(expected.canonicalJson()); + } + + private static SSLSession peerSession(String service) throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + try { + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service))); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + return session; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + return tls; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.createFile(directory.resolve("game-session-client.crt")).toString()); + tls.setPrivateKey(Files.createFile(directory.resolve("game-session-client.key")).toString()); + tls.setCaCert(Files.createFile(directory.resolve("account-ca.crt")).toString()); + return tls; + } +} From 9f1b75198b1f7cafd8d066dc271bf955484de4c7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:24:04 +1300 Subject: [PATCH 12/22] Implement registered issuer projection CAS and strengthen source transport proof --- .github/scripts/classify-change-scope.cjs | 2 + .../scripts/classify-change-scope.test.cjs | 21 + .github/workflows/ci.yml | 50 ++ build.gradle.kts | 20 +- ...dis-execution-with-aggregated-contracts.md | 2 +- .../game-logic-service/api-contracts.md | 4 +- .../game-session-service/api-contracts.md | 2 + .../game-session-service/runtime-and-data.md | 2 + design/architecture/repository-structure.md | 3 +- .../system-architecture-redis-lua-patterns.md | 4 +- .../system-architecture-shared-libraries.md | 6 +- design/project-management/ai-observations.md | 4 + .../player-access-and-session.md | 10 + ...hared-runtime-contracts-and-persistence.md | 4 +- .../common-redis-contracts/build.gradle.kts | 3 + .../contracts/RedisContractRegistry.java | 284 ++++++++ .../contracts/RedisInvocationContract.java | 41 ++ .../contracts/RedisScriptDescriptor.java | 264 ++++++++ .../contracts/RedisContractRegistryTest.java | 444 +++++++++++++ .../contracts/RedisScriptDescriptorTest.java | 229 +++++++ .../CommunicationAggregationService.java | 19 +- .../CommunicationAggregationServiceTest.java | 18 +- .../game-session-service/build.gradle.kts | 1 + ...ssuerAuthorityProjectionRedisContract.java | 104 +++ .../IssuerAuthorityProjectionTransitions.java | 610 ++++++++++++++++++ .../RedisIssuerAuthorityProjectionStore.java | 418 ++++++++++++ .../redis/issuer_authority_projection_cas.lua | 54 ++ ...suerAuthorityGrpcMtlsCrossServiceTest.java | 103 ++- ...orityGrpcPostgresMtlsCrossServiceTest.java | 275 ++++++++ ...thorityProjectionRedisIntegrationTest.java | 360 +++++++++++ ...rAuthorityProjectionRedisContractTest.java | 107 +++ ...uerAuthorityProjectionTransitionsTest.java | 399 ++++++++++++ ...disIssuerAuthorityProjectionStoreTest.java | 158 +++++ settings.gradle.kts | 3 + 34 files changed, 3969 insertions(+), 59 deletions(-) create mode 100644 services/common-redis-contracts/build.gradle.kts create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java create mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java create mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java create mode 100644 services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua create mode 100644 services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index e5273bceec..4386d34933 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -17,6 +17,7 @@ const ALL_SERVICES = [ const ALL_MODULES = [ "common-data-runtime", "common-platform-core", + "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -50,6 +51,7 @@ const SHARED_PREFIXES = [ "services/common-library/", "services/common-data-runtime/", "services/common-platform-core/", + "services/common-redis-contracts/", "services/common-saga/", "services/common-temporal/", "services/common-security/", diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 075a679e3f..022ea89092 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -261,6 +261,27 @@ test("shared modules force every Gradle module, including common-temporal", () = assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("hosted-environment-identity-controller")); }); +test("common Redis contracts use shared-library validation without becoming bootable", () => { + const result = classifyChangeScope([ + "services/common-redis-contracts/src/main/java/example/RedisContract.java", + ]); + + assert.equal(result.runAll, true); + assert.deepEqual(result.affectedModules, ALL_MODULES); + assert.equal(result.affectedModules.includes("common-redis-contracts"), true); + assert.equal(result.bootableModules.includes("common-redis-contracts"), false); +}); + +test("root Gradle build and settings changes include common Redis contract validation", () => { + for (const path of ["build.gradle.kts", "settings.gradle.kts"]) { + const result = classifyChangeScope([path]); + + assert.equal(result.runAll, true, path); + assert.equal(result.affectedModules.includes("common-redis-contracts"), true, path); + assert.equal(result.bootableModules.includes("common-redis-contracts"), false, path); + } +}); + test("controller and load-testing changes receive their own module checks", () => { const controllerResult = classifyChangeScope([ "services/hosted-environment-identity-controller/src/main/java/example/Controller.java", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2b0f68810c..4ee54eedce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,6 +59,7 @@ jobs: const completeModules = [ "common-data-runtime", "common-platform-core", + "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -1032,6 +1033,55 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Account PostgreSQL issuer readback socket mTLS composition proof + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:crossServiceTest \ + --tests crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#postgresIssuerSourceReturnsBootstrapCurrentAndHistoricalEvidenceOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#[1] clientIdentity = "wrong-service"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#[2] clientIdentity = "wrong-namespace"' \ + game-session-service + + - name: Upload Account PostgreSQL issuer readback socket mTLS proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-issuer-postgresql-readback-mtls-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/crossServiceTest/TEST-*AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run registered Game Session issuer projection Redis component proof + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSnapshots()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#gapAndAuthenticatedOlderDuplicateHaveDistinctNoMutationOutcomes()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#staleExpectedBytesAreNonMutatingThroughTheRegisteredOwnerScript()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration()' \ + game-session-service + + - name: Upload registered issuer projection Redis proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-issuer-projection-redis-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*IssuerAuthorityProjectionRedisIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session management owner UUID PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/build.gradle.kts b/build.gradle.kts index a8832406ea..4ebde85669 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -225,15 +225,17 @@ subprojects { dependencies { implementation(platform(libs.findLibrary("spring-boot-dependencies").get())) testImplementation(platform(libs.findLibrary("spring-boot-dependencies").get())) - implementation(libs.findLibrary("protobuf-java").get()) - implementation(libs.findLibrary("grpc-netty-shaded").get()) - implementation(libs.findLibrary("grpc-protobuf").get()) - implementation(libs.findLibrary("grpc-stub").get()) - implementation("javax.annotation:javax.annotation-api:1.3.2") - testImplementation(libs.findLibrary("spring-boot-starter-test").get()) - testImplementation(libs.findLibrary("spring-boot-starter-restclient-test").get()) - testImplementation(libs.findLibrary("spring-boot-resttestclient").get()) - testImplementation(libs.findLibrary("spring-boot-starter-webmvc-test").get()) + if (name != "common-redis-contracts") { + implementation(libs.findLibrary("protobuf-java").get()) + implementation(libs.findLibrary("grpc-netty-shaded").get()) + implementation(libs.findLibrary("grpc-protobuf").get()) + implementation(libs.findLibrary("grpc-stub").get()) + implementation("javax.annotation:javax.annotation-api:1.3.2") + testImplementation(libs.findLibrary("spring-boot-starter-test").get()) + testImplementation(libs.findLibrary("spring-boot-starter-restclient-test").get()) + testImplementation(libs.findLibrary("spring-boot-resttestclient").get()) + testImplementation(libs.findLibrary("spring-boot-starter-webmvc-test").get()) + } testRuntimeOnly(libs.findLibrary("junit-platform-launcher").get()) if (projectDir.parentFile.name == "services" && !name.startsWith("common-")) { testImplementation(testFixtures(project(":common-test-support"))) diff --git a/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md b/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md index 4525dd0ad0..f31dda9f8c 100644 --- a/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md +++ b/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is not implemented. The shared Redis-contract foundation, owner-local descriptor contributions, repository aggregation, ownership enforcement, and descriptor-driven proof remain gaps. +This decision is partially implemented. The narrow `common-redis-contracts` module provides immutable descriptors, explicit prefix ownership and invocation validation for role, principal, script identity/digest, key/argument arity and cluster slots. It has no executable owner scripts or automatic runtime wiring. Complete repository aggregation, existing-script/prefix coverage, ownership enforcement, descriptor-driven generic CI, rollout/coexistence evidence and deployed role/ACL proof remain gaps; a selected registered invocation does not establish those global guarantees. Current proof status remains in the [Shared Runtime tracker](../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#capability-status). ## Decision Record diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 1c9ef57cab..ce319bc596 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -21,7 +21,7 @@ This document defines the Game Logic Service REST and gRPC surfaces, exposure cl ### Communication Slice -- Live: `SendCommunication` accepts authenticated gameplay `SAY`, `WHISPER`, and `TELL` payloads, validates length, resolves room-scoped or direct-target delivery metadata, and forwards the normalized gameplay request projection to the Social & Groups stub with explicit type and recipient information. The current API returns speaker/target delivery metadata, structured per-recipient view metadata, and `shared.v1.ErrorDetail` codes so Game Session can render the canonical transcript and later recipient-delivery slices can consume the same gameplay result. This response-level error shape is current implementation drift against the owner classification above; focused migration proof is not yet complete. +- Live: `SendCommunication` accepts authenticated gameplay `SAY`, `WHISPER`, and `TELL` payloads, validates length, resolves room-scoped or direct-target delivery metadata, and forwards the normalized gameplay request projection to the Social & Groups regression stub with explicit type and recipient information. Game Logic validates `account_id` against the Account UUID contract in the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions), then forwards that exact value as `sender_id`; it does not trim/coerce the value or fall back to `character_id`. The current API returns speaker/target delivery metadata, structured per-recipient view metadata, and `shared.v1.ErrorDetail` codes so Game Session can render the canonical transcript and later recipient-delivery slices can consume the same gameplay result. This response-level error shape is current implementation drift against the owner classification above; focused migration proof is not yet complete. The regression stub proves UUID projection only: the live Social sender path remains numeric-account-keyed, so real Social integration and persistence are not proved and will reject this UUID until its tracked owner migration is completed. - Stubbed: downstream delivery still uses the Social & Groups regression stub that records gameplay `SendMessage` calls and echoes success while cross-service WebSocket and Telnet tests assert the canonical actor transcript and explicit recipient metadata. - Deferred: direct Social & Groups ingress for account messaging, ordinary group/channel communication, and ordinary account/social mail; published closed observer-view declarations; authored partial-observation mechanics; cross-pod delivery; type-specific history/acknowledgement; and profile-defined bounded `SHOUT`. These classes must not inherit a universal Game Logic dependency merely because an in-game adapter can invoke them. @@ -55,7 +55,7 @@ Expected response: - `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto). - `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome. -- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. +- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter validates `account_id` against the Account UUID identifier contract before Entity Management or Social calls; malformed, missing, noncanonical, or nil identity returns `INVALID_ARGUMENT`. It then projects the flat request to Social & Groups as `tenant_id`, the exact validated account UUID as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. This is shape validation and exact projection only; it does not establish a numeric-to-UUID mapping or complete caller binding. The real Social sender path remains numeric-account-keyed, so the current regression-stub proof does not establish real Social integration or persistence; see the [Social & Groups API implementation status](../social-groups-service/api-contracts.md#implementation-status). Game Logic does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and full projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. - `PickupVisibleRoomItem` and `DropCarriedItem` are the player-facing item selector RPCs for the current `GET` and `DROP` command path. Game Session sends the current session/game/room context, raw item reference, and quantity; Game Logic resolves names, visible refs, container identities, and stack-family refs against the appropriate visible holder before delegating the concrete mutation to Entity Management. - `ApplyActorCondition` is the current self-scoped gameplay orchestration path for the first actor-state mutation. It is not the target-state generic cross-actor effect API. - gRPC outcome selection follows the [canonical outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification): successfully produced gameplay/domain outcomes use the typed response contract, while a failure that prevents producing that result uses canonical non-OK status with bounded details. Exact RPC mappings remain implementation work. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index b92f9995c5..970a48b6ad 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -10,6 +10,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: +The dedicated source client, pure issuer-projection transition layer and registered owner-local Redis store remain unwired. The store uses an explicitly initialized Coordination connection rather than ambient Redis templates; it grants no recipient authorization. Executed component proof and remaining delivery, role/ACL, deployment and activation limits belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md); the issuer-projection contract remains owned by [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). + The dedicated `AccountIssuerAuthorityClient` is an unwired source-only consumer candidate for [Account's issuer readback](../account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). It requires file-backed mutual TLS and the exact Account server workload identity, validates current and explicitly selected historical evidence with the shared issuer-event codec, and compares canonical decimal counters without narrowing them. Its transport result is not a recipient membership snapshot, admission or rebind authorization, an installed issuer projection, or a delivered revocation. Runtime activation remains denied until the complete producer, mutual peer authentication, projection and negative proof passes; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records executed and unavailable proof. - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 5a6f92d8c3..7bc07415d5 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- The source-only issuer projection has an unwired decision layer and registered owner-local atomic Redis store. Its private, explicitly initialized Coordination client does not change the existing runtime client cohort or publish a bean; role/ACL deployment, authenticated event delivery and activation are unproved. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records the precise component and proof boundary; [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md) owns the projection semantics. + - Command ingress carries the canonical Account UUID unchanged into V9's `gameplay_command.account_uuid` slot; an absent Account identity does not invent either a UUID or private numeric selector. Existing numeric row evidence is retained without guessed mapping or backfill. Retained-command replay, complete owner/consumer handoff and activation remain unproved; component implementation and proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). - The management-owner correction in [#2929](https://github.com/benhook1013/FireMUD/pull/2929) adds `game_instances.owner_account_uuid` and retains raw numeric owner evidence unchanged and unmapped. New requests and owner-self checks use canonical UUIDs; this supplies neither Account operator-reference/digest authorization nor catalog activation. Current component, PostgreSQL and composed-child proof limits remain in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/repository-structure.md b/design/architecture/repository-structure.md index 546b249189..33ed4452ad 100644 --- a/design/architecture/repository-structure.md +++ b/design/architecture/repository-structure.md @@ -25,6 +25,7 @@ root │ ├── automation-scripting-service/ │ ├── common-data-runtime/ │ ├── common-platform-core/ +│ ├── common-redis-contracts/ │ ├── common-saga/ │ ├── common-security/ │ ├── common-temporal/ @@ -79,7 +80,7 @@ root - `gradle/` – Gradle version catalog, build conventions, and wrapper binaries. - `k8s/` – Kubernetes base manifests, Helm charts, overlays, monitoring configs, network policies, preview/prod support assets, storage/database helpers, Velero backup assets, and Terraform modules for local and production-like clusters. - `protos/` – Versioned gRPC definitions for every service, organized by service and version as described in this directory’s [gRPC API Style & Versioning Guidelines](./system-architecture-grpc.md). -- `services/` – Spring Boot microservices plus the narrowly scoped shared platform/library Gradle modules (`common-data-runtime`, `common-platform-core`, `common-saga`, `common-security`, `common-temporal`, `common-test-support`, and `common-web-support`), including Flyway database migration scripts under `services//src/main/resources/db/migration/` and shared saga migrations under `services/common-saga/src/main/resources/db/migration/saga`. SQL-backed services use one explicit `jOOQ + Flyway` persistence model rather than a mixed long-term ORM stack, and long-running durable control-plane workflows use the shared Temporal substrate rather than service-local workflow scaffolding. ADR 0176's future narrow Redis-contract foundation does not make owner-exclusive Redis execution a shared module concern. +- `services/` – Spring Boot microservices plus the narrowly scoped shared platform/library Gradle modules (`common-data-runtime`, `common-platform-core`, `common-redis-contracts`, `common-saga`, `common-security`, `common-temporal`, `common-test-support`, and `common-web-support`), including Flyway database migration scripts under `services//src/main/resources/db/migration/` and shared saga migrations under `services/common-saga/src/main/resources/db/migration/saga`. SQL-backed services use one explicit `jOOQ + Flyway` persistence model rather than a mixed long-term ORM stack, and long-running durable control-plane workflows use the shared Temporal substrate rather than service-local workflow scaffolding. The initial `common-redis-contracts` descriptor/validation foundation follows ADR 0176; owner-exclusive Redis builders, adapters and executable Lua remain in their service. Complete repository aggregation and legacy script coverage are still open. - `web-client/` – React web application. - `.editorconfig` – Consistent indentation and newline settings across editors. - `.env.sample` – Example environment variables loaded by `docker compose` and the test suites. diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 902bd50d01..74e6b566bd 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -419,9 +419,9 @@ Script changes must be rolled out in a way that respects both AOF replay semanti - `schemaVersion` changes must support every caller and stored-payload version in the evidenced coexistence set; unknown or ambiguous versions, including unproven missing versions, must fail before mutation with `"UNSUPPORTED_SCHEMA_VERSION"` or the equivalent so AOF replay cannot apply effects with mismatched schemas. - When a reset-required change is introduced, operators follow the reset runbooks so that any surviving AOF history for old scripts is discarded for the relevant scope rather than replayed under incompatible semantics. -## Target-State Lua Script Registry and CI Expectations (Not Implemented) +## Target-State Lua Script Registry and CI Expectations (Partial Implementation) -The registry, validators, ownership enforcement, generic test harness, and CI checks in this section are target state and are not currently implemented. Once delivered, all coordination-related Lua scripts contribute entries to one aggregated **Lua Script Registry**. The shared Redis-contract foundation owns the registry schema and aggregation; each owning service contributes entries and retains executable Lua for exclusive key families. For each script, the registry records: +The initial `common-redis-contracts` foundation validates explicitly contributed descriptors and invocation handles, including owner/prefix, role/principal, identity/digest, arity and cluster-slot checks. It does not inventory or register legacy scripts automatically. Complete repository aggregation, ownership enforcement, the generic test harness, all-script CI and deployed role/ACL proof remain target-state gaps. Once delivered, all coordination-related Lua scripts contribute entries to one aggregated **Lua Script Registry**. The shared Redis-contract foundation owns the registry schema and aggregation; each owning service contributes entries and retains executable Lua for exclusive key families. For each script, the registry records: - Script identifier and file path. - Expected `KEYS` and `ARGV` ordering and allowed prefixes (including hash-tag rules). diff --git a/design/architecture/system-architecture-shared-libraries.md b/design/architecture/system-architecture-shared-libraries.md index 3d0d7daf9b..425a5b2dc7 100644 --- a/design/architecture/system-architecture-shared-libraries.md +++ b/design/architecture/system-architecture-shared-libraries.md @@ -6,7 +6,7 @@ FireMUD's microservices share a set of narrowly scoped modules so each service c ## Implementation Status -The current `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so shared code must not synthesize an absent epoch; exact tuple propagation and final enforcement remain implementation and focused-proof gaps at that boundary. The narrow shared Redis-contract foundation, owner-local descriptor contributions, repository aggregation, ownership enforcement, and descriptor-driven proof required by [ADR 0176](./decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md) are not implemented. See the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current status and proof evidence. +The current `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so shared code must not synthesize an absent epoch; exact tuple propagation and final enforcement remain implementation and focused-proof gaps at that boundary. The initial `common-redis-contracts` descriptor/validation slice follows [ADR 0176](./decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md); it is opt-in and contains no owner-exclusive execution or automatic Redis client wiring. Complete owner contributions, repository aggregation, ownership enforcement, generic CI and deployed role/ACL proof remain incomplete. Shared proof status belongs to the [Shared Runtime tracker](../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#capability-status); scripting consequences remain in the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). - `common-saga` adoption is not currently explicit: base service conventions add the dependency broadly, and deployed service configurations expose the Saga Flyway location even for services without a Saga workflow. This can materialize shared Saga tables and repositories outside the adopter boundary; the explicit adopter allowlist and focused conformance proof remain incomplete. @@ -51,7 +51,7 @@ DTO records for common tasks (paging, IDs, basic metadata) live here so services ### Redis Key Naming & Lua Script Helpers -Target-state Redis helpers must follow the owner-local execution and aggregated-contract boundary in [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md); this boundary is not implemented in the current tree. +Target-state Redis helpers follow the owner-local execution and aggregated-contract boundary in [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md). The current foundation validates selected contributed descriptors and immutable invocation handles; the full aggregated boundary is not yet implemented. The target narrow shared Redis-contract module would own the descriptor schema, common outcome types, Redis-role and prefix-owner rules, hash-tag/cluster-slot validation, compatibility metadata rules, and repository registry/test aggregation. It would own executable key builders, invocation machinery, or Lua only for mutations genuinely executed by multiple independently deployed callers. @@ -85,7 +85,7 @@ Shared code is organized as the narrowly scoped Gradle modules currently include The versioned definitions under `protos/` remain the source for generated service stubs; they are not a replacement for the split Java modules. If a module is published for a supported distribution workflow, it retains its module-specific coordinates under the `net.firedevops.firemud` group rather than being folded into one shared runtime artifact. -Redis contracts follow [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md): a future narrow foundation such as `common-redis-contracts` may carry descriptor schemas, bounded outcomes, role/owner/slot validation, and repository aggregation. Owner-exclusive Redis builders, adapters, executable Lua, and semantic tests remain in the owning service. The foundation is not evidence that this target module or its registry has been implemented. +Redis contracts follow [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md). The narrow `common-redis-contracts` module carries the initial descriptor schema, bounded outcomes and role/owner/principal/slot invocation validation. Owner-exclusive Redis builders, adapters, executable Lua and semantic tests remain in the owning service. Repository aggregation, full legacy registration and deployed caller/ACL proof remain incomplete; presence of this module does not establish them. This split-module boundary aligns with the [Shared Runtime, Service Contracts, and Persistence implementation tracking](../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md) record and keeps reuse explicit without globalizing owner-exclusive execution. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 674ff30c18..3f7b0f7cc7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -225,3 +225,7 @@ Entry format: - `2026-10-02`: Match long Gradle report filenames separately from JUnit suite identities - Context: exact CI36947366507 strictly proved the eight reset cases and eleven retained-association cases, but artifact paths using the literal suite name missed the producer and retained-association XML. The actual producer filename was `TEST-integ-LL300RMKP9ANC.net.firedevops.firemud.accountservice.PasswordResetAuthorityProducerPostgresIntegrationTest.xml`, while its XML retained the canonical full suite name. - Expected pattern: use class-bounded filename globs for artifact capture and retain exact canonical suite/case identities in the strict verifier. Prove the glob matches the actual reports; an upload success with one file is not evidence that every intended suite was retained. Keep execution-log proof distinct from missing raw XML and require a subsequent runner outcome for the corrected capture path. + +- `2026-10-02`: Keep helper file targets and validation inside the pinned assignment + - Context: a helper assigned to the isolated Unit 1B worktree accidentally created an empty `DO_NOT_USE.java` in the default checkout, reported it, and removed its own disposable file; the orchestrator confirmed it was absent. Another helper ran an unrequested diff check despite a validation-none assignment. No user change or useful implementation was lost, and neither action supplied credited validation. + - Expected pattern: verify the worktree identity before edits, use absolute patch targets, and treat validation-none as a closed boundary rather than permission for substitute checks. Report scope mistakes immediately and distinguish recovery from canonical proof; a successful helper handoff does not substitute for orchestrator inspection and validation. 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 135d284088..b28d3d4d0f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,16 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The prepared [#2933](https://github.com/benhook1013/FireMUD/pull/2933) correction adds an unwired Game Session issuer-projection transition engine and a registered owner-local byte-exact Redis compare-and-set store on an explicitly initialized Coordination connection. It accepts only the dedicated Account client's verified readback for the configured workload namespace, binds the exact issuer/stream/current or historical event evidence, denies gaps and conflicting progress, and atomically updates the projection and checkpoint without TTL. Duplicate verification is non-mutating; old events require Account's exact immutable historical lookup. This derived projection grants neither admission nor rebind authority. The narrow shared Redis descriptor foundation is partial; complete existing-script aggregation, descriptor-driven global CI, client-cohort cutover, deployed role/ACL proof, event delivery and active-binding revocation remain required. The new PostgreSQL-through-socket-mTLS and Redis integration cases are focused component proof, not deployment or runtime activation. + +Exact published [CI 36959528382](https://github.com/benhook1013/FireMUD/actions/runs/36959528382) at `58695d165a03f6004236a8a5e27b1a99f1b0eae4` completed with aggregate failure. Raw XML proved all fifteen issuer PostgreSQL, seventeen retained-association and four snapshot cases executed without skips, failures or errors, along with six reset-producer and both required reset-application methods. Five of six socket mTLS cases passed; the missing-client-certificate assertion lost its underlying throwable, so its cause cannot be established from that result. The corrected test observes the certificate rejection directly with explicit trust-only credentials, bounded timeouts, HTTP/2 negotiation and diagnostics. LOGIN/PLAY/LOOK passed; all four remaining TCP chat-output failures were the Game Logic numeric Account validator rejecting the canonical UUID. The local correction preserves exact UUIDs through Game Logic, but Social's numeric sender store still needs its owner migration; a Social stub does not prove persistence or end-to-end delivery. + +The corrected combined Redis foundation/Game Logic/Game Session/TCP full checks, Game Session/TCP boot JARs, links and Markdown passed 221 tasks (45 executed, 176 up-to-date), including formatting, Checkstyle, SpotBugs and JaCoCo. Foundation's twenty unit cases and Game Logic's 91 unit/five integration results were reused from their earlier same-code green gate; Game Logic's boot JAR also passed there. Game Session executed 1,850 unit, eighteen integration and seven cross-service cases, with 17/149/35 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. All executed cases were clean, including fourteen transition, three descriptor, five store and six physical socket mTLS cases. Twenty-five CI-classifier cases and the lightweight scope contract passed. All six Redis integration cases and both PostgreSQL/socket test methods skipped locally without Docker; the latter defines three intended runner cases when parameterized execution is enabled. Strict CI requires their execution and captures raw XML. Fresh runner composition, fresh-image/live identity, membership RPC, credential/context/catalog activation and Account key-ring delivery/readiness remain gates; the RPC and credential paths stay denied and the ring mount remains unpublished. Unit 1B is provisional. + +### Preceding local checkpoint evidence + +The following paragraphs describe the earlier transport-only candidate and its local gate, not the subsequently completed runner or the prepared projection correction. + The current [#2933](https://github.com/benhook1013/FireMUD/pull/2933) candidate adds exact historical issuer-event/current-checkpoint readback and the dedicated, closed issuer-source RPC contract at [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). Its Account handler requires the exact Game Session workload peer; its Game Session client requires the exact Account server peer and validates complete current/selected historical source evidence with arbitrary-precision counters. Both remain unwired. Nine producer unit, ten handler unit, fifteen client unit and six real-socket mTLS cases executed cleanly locally. The physical tests cover successful current/historical reads, trusted wrong-service/wrong-namespace callers and servers, and missing-client-certificate handshake rejection. They mock the owner-local producer, so they do not prove a combined PostgreSQL/transport transaction, delivered revocation, projection installation or live credentials. All fifteen issuer PostgreSQL cases compiled but skipped locally without Docker; the preceding exact-head runner proved twelve before the three historical-read cases were added. The existing CI strict proof mechanism now requires those additional cases and retains the six socket-case XML results before broader transport checks. The corrected combined Common Security/Game Logic/Account/Common Platform/Game Session/TCP checks and three affected boot JARs, links and Markdown passed 256 tasks (88 executed, 168 up-to-date), including formatting, Checkstyle, SpotBugs and JaCoCo. Common Security executed 120 unit cases, including all 28 gameplay-attestation cases; Game Logic executed 91 unit and five integration cases; Account executed 545 unit cases with all 182 PostgreSQL cases skipped; Game Session executed 1,828 unit, eighteen integration and seven cross-service cases, with 17/143/33 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. Common Platform's 139 unit results were reused from the preceding same-code gate. Executed cases were clean. The new exact-head runner still must execute historical database and composed transport proof. Fresh-image and live activation proof remain open; the protobuf generator succeeded, while local `buf lint` is unavailable because `buf` is not installed. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 69cfc56e02..47da406dcb 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for shared runtime, service contr The implementation record below summarizes the shared runtime, service-contract, orchestration, persistence, and workflow boundaries represented by this tracker. It distinguishes live implementation from bounded follow-up work; it does not claim that every future service, runtime consumer, or workflow family has already adopted these conventions. +The initial `common-redis-contracts` module implements the ADR 0176 descriptor and selected-invocation validation boundary: explicit owner/principal/role prefix declarations, versioned identity/digest, ordered key/argument arity, immutable invocation handles and Redis Cluster tag/slot checks. It has no Redis client, automatic runtime wiring or shared owner-exclusive executable. Its focused unit tests executed locally; consolidated static checks and the owner adapter's runtime proof are recorded at their actual checkpoint rather than inferred from the descriptor. Full legacy prefix/script inventory, repository aggregation and all-script CI, rollout/coexistence evidence, role-qualified deployment and ACL proof remain required. Existing generic clients are not cut over by introducing this library. + Account V29 now persists one immutable canonical UUID per Account while preserving the numeric local primary key, with explicit migration/insertion provenance and source-row evidence. The Account repository returns and resolves that UUID using exact source-row readback, while external Account carriers and consumers remain numeric; this does not establish a tenant UUID mapping. `:account-service:spotlessJavaCheck` and the focused `AccountLoginAuthModesTest` executed successfully; the focused `AccountRepositoryIntegrationTest` compiled but all 13 cases, including the V29 retained-row, JOIN-operation, and membership-receipt no-loss proof, were skipped because Docker was unavailable. PostgreSQL runtime behavior is therefore not yet verified. The broader `SF-1.2` capability remains partial and its cross-service UUID convergence is still unproved. Account V25, Game Session V2, and Automation V2 schema activation now has a bounded quiescence slice: base/hosted workloads use non-rolling replacement, the trusted dev-demo path recognizes migration-bearing pushes, preserves that runtime database, stops the three Account, Game Session, and Automation writer Deployments, and verifies their Pods are absent; ordinary pushes retain the established clean namespace reset. Redispatch classification uses the exact namespace-manager deployed-head annotation and fails before mutation if the head or Git ancestry is unproven. The Game Session and Automation V2 migrations check their known V1 indexes plus service-specific active-claim/data prerequisites before changing indexes; this status does not claim equivalent migration validation for Account V25. Focused PostgreSQL failure-path tests are added but remain unverified until Docker-backed service tests run. Candidate PR previews that change Flyway migrations fail before namespace recreation because their scoped runtime path cannot prove Postgres PVC provenance or query migration history; trusted post-merge deployment is the activation path. Recovery is roll-forward only. This does not complete the separate retained-row identity and cross-instance PostgreSQL proof recorded below. @@ -83,7 +85,7 @@ The following current-state findings refine the existing partial/drift status; o | `SF-1.2` Identifiers, tenant context, and routing identity primitives | `partial`: Shared request/runtime identity validation and tenant-aware contexts are live, but durable cross-boundary identity still uses numeric forms instead of ADR 0020 scoped UUIDs, and gameplay delegation has not converged on canonical typed unsigned `PlayerExecutionContext`; legacy gameplay-attestation helpers remain wired into gameplay consumers pending removal. | `drift-found`: current context/scope tests prove useful fields but not the accepted workload/context boundary; `GameplaySessionAttestationServiceTest` proves helper token validation/matching only, and no focused consumer-level proof establishes that attestation values cannot authorize delegated work, establish workload identity, or serve as replay authority. | [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md) | [`RequestIdValidation.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/RequestIdValidation.java); [`RuntimeIdentity.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [`SessionContext.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java); [`GameplaySessionAttestationService.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java) | [`RequestIdValidationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/RequestIdValidationTest.java); [`SessionContextTenantAccessTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java); [`GameplaySessionAttestationServiceTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java) | [Player Access](./player-access-and-session.md); [Realm Routing](./realm-routing-and-playable-state.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Migrate durable cross-boundary identifiers to scoped UUIDs with owner/scope validation; converge on one typed unsigned execution context, retain complete scoped validation, and prove it adds no authorization-store round trip; remove the deprecated gameplay-attestation debt, and add focused consumer proof before claiming that it cannot authorize delegated work. | | `SF-1.3` Authentication, authorization, trust, secrets, and certificates | `partial`: JWT propagation/claims, gRPC and HTTP auth interceptors, and mTLS configuration/reload are live, but signing still uses shared HMAC material and canonical certificate-derived workload identity, method caller allowlists, receiver-specific token profiles, issued-token/auth-generation enforcement, and rotation remain incomplete. Legacy gameplay attestations remain wired into gameplay consumers pending removal. | `drift-found`: current JWT/TLS tests prove bounded existing seams but do not prove Account-only asymmetric issuance and JWKS validation, concrete peer-certificate identity, exact per-method workload authorization, receiver-specific token enforcement, or Account-owned auth-generation enforcement; generic HMAC/internal-token behavior remains implementation debt, and no focused consumer-level proof establishes that legacy attestation values cannot authorize delegated work, establish workload identity, or serve as replay authority. | [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md); [security](../../architecture/system-architecture-security.md); [authentication](../../architecture/system-architecture-authentication.md); [ADR 0014](../../architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md); [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md); [ADR 0037](../../architecture/decisions/adr-0037-fail-closed-token-authority-outages-with-bounded-active-gameplay.md); [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) | [`GrpcClientAuth.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java); [`AuthTokenInterceptor.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java); [`ReloadableJwtUtil.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`apps.yaml`](../../../k8s/helm/firemud/templates/apps.yaml) | [`GrpcClientAuthTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java); [`AuthTokenInterceptorTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [`GameplaySessionAttestationServiceTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java); [`AuthConfigTest.java`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AuthConfigTest.java) | [Player Access](./player-access-and-session.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Platform Operations](./platform-operations-and-delivery.md) | Shared signing material reaches workloads beyond Account and multiple workloads can mint locally; validators do not use Account JWKS. Certificate-bound workload identities, default-deny method allowlists, receiver-specific token enforcement, issued-token registry/auth-generation enforcement, generic internal-token removal, and rotation proof are absent. Consumer-level proof that deprecated gameplay-attestation values cannot authorize delegated calls, establish workload identity, or serve as replay authority is also absent; removal remains required. Player-facing readiness stays blocked pending Account-only private signing, asymmetric validator convergence, certificate-derived caller enforcement, monotonic generation projection/validation, phased rotation/compromise proof, and removal of the obsolete gameplay-attestation implementation debt. | | `SF-1.4` Clocks, timestamps, durations, and time semantics | `partial`: The proto time-field guard, explicit wall-clock fields, and tick-relative command/scheduler fields are live; a shared gameplay clock/state API and broad timed-state adoption are not. | `proven` for the naming guard and current tick/time contract seams, not runtime-wide time semantics. | [scheduler and timers](../../architecture/system-architecture-scripting-scheduler-and-timers.md); [runtime execution](../../architecture/system-architecture-scripting-runtime-execution.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [`check-proto-time-fields.py`](../../../dev-tools/validation/check-proto-time-fields.py); [`automation_scripting_service.proto`](../../../protos/automation-scripting/v1/automation_scripting_service.proto); [`TextCommandDefinition.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDefinition.java); [`ActionStateCommandHandler.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) | [`test_check_proto_time_fields.py`](../../../dev-tools/validation/test_check_proto_time_fields.py); [`AuthoredActionCommandHandlerTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [`TickSchedulerTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java) | [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Gameplay](./gameplay-rules-entities-and-effects.md) | Runtime cooldown state, common buff/condition timing, scheduled-effect execution, and richer gameplay-clock APIs remain gaps. The guard proves naming only; no scheduler design decision is made here. | -| `SF-1.5` Shared libraries, interceptors, and contract helpers | `partial`: Split shared platform, data, security, saga, and Temporal modules provide live auto-configuration, interceptors, identity, Redis, persistence, and workflow helpers; the broader shared-library substrate is not complete. | `drift-found`: current shared module/interceptor/helper implementation seams are proven, but the shared Redis descriptor/aggregation/helper foundation and descriptor-driven proof remain absent. | [shared libraries](../../architecture/system-architecture-shared-libraries.md); [gRPC](../../architecture/system-architecture-grpc.md); [transactions](../../architecture/system-architecture-transactions.md) | [`CommonGrpcServerConfiguration.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/CommonGrpcServerConfiguration.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`CommonTemporalAutoConfiguration.java`](../../../services/common-temporal/src/main/java/net/firedevops/firemud/common/temporal/config/CommonTemporalAutoConfiguration.java) | [`GrpcTlsReloadPolicyTest.java`](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcTlsReloadPolicyTest.java); [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`CommonSecurityAutoConfigurationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java); [`FiremudWorkflowIdsTest.java`](../../../services/common-temporal/src/test/java/unit/net/firedevops/firemud/common/temporal/FiremudWorkflowIdsTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Split `common-*` module ownership is converged in the canonical shared-libraries document. The shared Redis key/Lua descriptor, aggregation, and helper foundation required by ADR 0176 is not present in this tree; implement and prove that target boundary before completion. This row records no new design decision. | +| `SF-1.5` Shared libraries, interceptors, and contract helpers | `partial`: Split shared platform, data, security, saga and Temporal modules provide live helpers; the opt-in `common-redis-contracts` module adds initial descriptor and selected-invocation validation, not complete Redis adoption. | `drift-found`: focused descriptor tests execute, but repository aggregation, legacy coverage, generic CI and deployed caller/ACL proof remain incomplete. | [shared libraries](../../architecture/system-architecture-shared-libraries.md); [gRPC](../../architecture/system-architecture-grpc.md); [transactions](../../architecture/system-architecture-transactions.md) | [`CommonGrpcServerConfiguration.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/CommonGrpcServerConfiguration.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`CommonTemporalAutoConfiguration.java`](../../../services/common-temporal/src/main/java/net/firedevops/firemud/common/temporal/config/CommonTemporalAutoConfiguration.java); [`RedisContractRegistry.java`](../../../services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java) | [`GrpcTlsReloadPolicyTest.java`](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcTlsReloadPolicyTest.java); [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`CommonSecurityAutoConfigurationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java); [`FiremudWorkflowIdsTest.java`](../../../services/common-temporal/src/test/java/unit/net/firedevops/firemud/common/temporal/FiremudWorkflowIdsTest.java); [`RedisContractRegistryTest.java`](../../../services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Split `common-*` ownership follows the canonical shared-libraries document and ADR 0176. Complete the remaining aggregate catalog, ownership/role-client adoption and focused proof before claiming the shared boundary complete. This row records no new design decision. | | `SF-2.1` PostgreSQL ownership, schemas, migrations, and retention | `partial`: `jOOQ + Flyway`, owning service schemas, generated access, schema-qualified saga migrations, and several service-local retention sweeps are live. Shared retention-class declarations, cross-service horizon compatibility and blockers, safe-watermark cleanup, holds, and complete focused proof remain unimplemented; one gateway persistence surface also remains unresolved. | `drift-found`: current tests prove bounded jOOQ/Flyway/schema-qualified persistence and service-local retention seams only; they do not prove the SQL-only migration lineage, explicit Saga adopter wiring, historical migration mappings, shared retention contract, or cross-service cleanup safety. | [database migrations](../../architecture/system-architecture-database-migrations.md); [transactions](../../architecture/system-architecture-transactions.md); [scaling and retention](../../architecture/system-architecture-scaling-runbook.md#data-retention-and-high-churn-tables); [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) | [`FiremudJooqConventionsPlugin.kt`](../../../buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt); [`JooqPersistenceSupport.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/persistence/jooq/JooqPersistenceSupport.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`application.yml`](../../../services/game-session-service/src/main/resources/application.yml); [`Game Session V1__baseline.sql`](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [`PlayerCommandHistoryRetentionSweepJob.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryRetentionSweepJob.java); [`DurableResumeTranscriptExpiryJob.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJob.java); [`ScriptOutboxCleanupJob.java`](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptOutboxCleanupJob.java); [`V1__init.sql`](../../../services/spring-cloud-gateway/src/main/resources/db/migration/V1__init.sql) | [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`PostgresBackedServiceTestSupport.java`](../../../services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java); [`SagaPersistenceRepositoryIntegrationTest.java`](../../../services/common-saga/src/test/java/integration/net/firedevops/firemud/common/saga/persistence/SagaPersistenceRepositoryIntegrationTest.java); [`PlayerCommandHistoryRetentionSweepJobTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryRetentionSweepJobTest.java); [`DurableResumeTranscriptExpiryJobTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java); [`ScriptWorkItemServiceImplTest.java`](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java); [`check-flyway-versions.py`](../../../dev-tools/validation/check-flyway-versions.py) | [Game Session](./game-session-runtime-and-tick-coordination.md); [World Runtime](./world-runtime-and-movement.md); [Game Authoring](./game-authoring-publishing-and-activation.md); [Platform Operations](./platform-operations-and-delivery.md) | ADRs 0079-0082 accept the single persistence stack, adopter-local schema ownership, objective compatibility gates, and semantic identifier-migration boundary. The canonical retention contract and operational consequences are owned by ADR 0163 and the scaling runbook; current service-local sweeps do not establish the shared declarations, horizon inequalities and blockers, safe-watermark cleanup, hold handling, or required focused proof. Gateway `V1__init.sql` creates `route_config`, while runtime routes use [`GatewayRouteServiceImpl.java`](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java) with no jOOQ owner; migration compatibility evidence, shared-migration versioning, generic mapping/orchestration, and focused proof remain incomplete. | | `SF-2.2` Redis coordination, caching, rate limiting, and reset semantics | `partial`: Shared Redis configuration, atomic counters, bounded caches, session/presence coordination, rate limiting, replay guards, and tick Lua seams are live; cross-service reset and script conventions are incomplete. | `proven` for the current shared Redis primitives and named coordination/cache/replay adopters, not the whole reset contract. | [Redis](../../architecture/system-architecture-redis.md); [Redis cache](../../architecture/system-architecture-redis-cache.md); [Redis reset and recovery](../../architecture/system-architecture-redis-reset-and-recovery.md); [Redis Lua patterns](../../architecture/system-architecture-redis-lua-patterns.md) | [`RedisProperties.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/RedisProperties.java); [`RedisAtomicOperations.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/redis/RedisAtomicOperations.java); [`RedisSessionContextService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [`tick_commit.lua`](../../../services/game-session-service/src/main/resources/redis/tick_commit.lua); [`GameplayHandshakeFilter.java`](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java) | [`RedisAtomicOperationsTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/redis/RedisAtomicOperationsTest.java); [`RedisSessionContextServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [`RedisMovementEffectIdempotencyServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [`GameplayHandshakeFilterTest.java`](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Platform Operations](./platform-operations-and-delivery.md) | ADRs 0083-0087 accept the no-general-broker boundary, evidence-scoped Lua compatibility, evidence-gated replay/reset, owner-validated cache classes, and isolated-subject rate-limit semantics. Shared key/script descriptors, coexistence evidence, the durable recovery controller and external fence, room-cache validation, and repo-wide rate-limit/outage proof remain incomplete. Auth allowlist, issued-token registry, and authority-generation consumption are also absent; see `SF-1.3`. | | `SF-2.3` Idempotency, outbox, replay, and reconciliation | `partial`: Durable tick/effect ledgers, Redis idempotency/replay, remote-followup reconciliation, Entity nonblank-`effectId` replay and blank-ID denial, and Automation work-item/outbox paths are live; coverage is owner- and domain-bounded. | `drift-found` | [transactions](../../architecture/system-architecture-transactions.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [runtime execution](../../architecture/system-architecture-scripting-runtime-execution.md); [ADR 0083](../../architecture/decisions/adr-0083-no-general-event-broker-until-measured-adoption-gates.md); [ADR 0120](../../architecture/decisions/adr-0120-owner-read-first-control-plane-notifications.md); [scripting control-plane events](../../architecture/system-architecture-scripting-control-plane-events.md) | [`TickBatchExecutionService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [`RedisDurableGameplayReplayService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisDurableGameplayReplayService.java); [`RemoteFollowupRuntimeServiceImpl.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [`EntityMutationEffectReplayService.java`](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java); [`ScriptWorkItemServiceImpl.java`](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java) | [`TickBatchExecutionServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [`RemoteFollowupRuntimeServiceImplTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [`RedisMovementEffectIdempotencyServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [`EntityMutationEffectReplayServiceTest.java`](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java); [`ScriptWorkItemExecutionServiceImplTest.java`](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java) | [Game Session](./game-session-runtime-and-tick-coordination.md); [Gameplay](./gameplay-rules-entities-and-effects.md); [Automation](./automation-and-scheduler-runtime.md); [World Runtime](./world-runtime-and-movement.md) | Entity service/gRPC unit proof covers blank-ID denial but not trusted caller identity, SQL/PostgreSQL uniqueness, concurrent first-apply, operation/target/request conflict rejection, or in-progress-marker recovery. The named tick, follow-up, and Automation work-item tests remain bounded and do not establish a repo-wide outbox contract. Target ownership remains in the linked transactions, scripting execution, and control-plane event documents. | diff --git a/services/common-redis-contracts/build.gradle.kts b/services/common-redis-contracts/build.gradle.kts new file mode 100644 index 0000000000..f6727627a1 --- /dev/null +++ b/services/common-redis-contracts/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + `java-library` +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java new file mode 100644 index 0000000000..588fa2e818 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** Validates owner declarations and prepares immutable invocation contracts. */ +public final class RedisContractRegistry { + + private static final int REDIS_CLUSTER_SLOT_COUNT = 16384; + private final Map descriptorsById; + + public RedisContractRegistry( + Collection prefixDeclarations, + Collection descriptors) { + Objects.requireNonNull(prefixDeclarations, "prefixDeclarations are required"); + Objects.requireNonNull(descriptors, "descriptors are required"); + if (prefixDeclarations.isEmpty()) { + throw new IllegalArgumentException("at least one owner prefix declaration is required"); + } + + Map byPrefix = new HashMap<>(); + List declarations = new ArrayList<>(prefixDeclarations); + Set uniqueDeclarations = new HashSet<>(); + for (PrefixDeclaration declaration : declarations) { + Objects.requireNonNull(declaration, "prefix declaration is required"); + if (!uniqueDeclarations.add(declaration)) { + throw new IllegalArgumentException( + "duplicate owner prefix declaration: " + declaration.prefix()); + } + PrefixDeclaration existing = byPrefix.putIfAbsent(declaration.prefix(), declaration); + if (existing != null) { + throw new IllegalArgumentException( + "conflicting owner prefix declarations: " + declaration.prefix()); + } + } + rejectOverlappingOwnership(declarations); + + Map byId = new HashMap<>(); + Set resourcePaths = new HashSet<>(); + for (RedisScriptDescriptor descriptor : descriptors) { + Objects.requireNonNull(descriptor, "script descriptor is required"); + if (byId.putIfAbsent(descriptor.scriptId(), descriptor) != null) { + throw new IllegalArgumentException("duplicate script identifier: " + descriptor.scriptId()); + } + if (!resourcePaths.add(descriptor.resourcePath())) { + throw new IllegalArgumentException( + "duplicate script resource path: " + descriptor.resourcePath()); + } + validateDeclaredOwnership(descriptor, byPrefix); + } + + this.descriptorsById = Map.copyOf(byId); + } + + /** + * Validates all supplied invocation metadata before returning a handle. The returned handle is + * declarative only; this registry does not load or execute Redis scripts. + */ + public RedisInvocationContract prepareInvocation(InvocationRequest request) { + Objects.requireNonNull(request, "invocation request is required"); + RedisScriptDescriptor descriptor = descriptorsById.get(request.scriptId()); + if (descriptor == null) { + throw new IllegalArgumentException("unregistered script identifier: " + request.scriptId()); + } + + requireEquals(descriptor.resourcePath(), request.resourcePath(), "script resource path"); + requireEquals(descriptor.sha256(), request.sha256(), "script SHA-256 digest"); + requireEquals(descriptor.owner(), request.owner(), "script owner"); + requireEquals(descriptor.principal(), request.principal(), "Redis principal"); + requireEquals(descriptor.role(), request.role(), "Redis role"); + + if (request.keys().size() != descriptor.keys().size()) { + throw new IllegalArgumentException( + "KEYS arity mismatch: expected " + + descriptor.keys().size() + + ", got " + + request.keys().size()); + } + if (request.arguments().size() != descriptor.arguments().size()) { + throw new IllegalArgumentException( + "ARGV arity mismatch: expected " + + descriptor.arguments().size() + + ", got " + + request.arguments().size()); + } + + Integer commonSlot = null; + String commonTag = null; + for (int index = 0; index < descriptor.keys().size(); index++) { + RedisScriptDescriptor.KeySpec keySpec = descriptor.keys().get(index); + String key = request.keys().get(index); + if (key.isEmpty() + || containsControlCharacter(key) + || !key.startsWith(keySpec.ownedPrefix())) { + throw new IllegalArgumentException( + "KEYS[" + index + "] does not match its declared owner prefix"); + } + + if (keySpec.hashTagDeclaration() == RedisScriptDescriptor.HashTagDeclaration.REQUIRED) { + String tag = extractHashTag(key); + if (tag == null) { + throw new IllegalArgumentException( + "KEYS[" + index + "] is missing a non-empty Redis hash tag"); + } + int slot = clusterSlot(key); + if (commonTag != null && !commonTag.equals(tag)) { + throw new IllegalArgumentException("multi-key invocation uses different Redis hash tags"); + } + if (commonSlot != null && commonSlot != slot) { + throw new IllegalArgumentException("multi-key invocation crosses Redis Cluster slots"); + } + commonTag = tag; + commonSlot = slot; + } + } + + return new RedisInvocationContract(descriptor, request.keys(), request.arguments(), commonSlot); + } + + /** Returns the Redis Cluster slot for a key using the first non-empty {@code {...}} tag. */ + public static int clusterSlot(String key) { + Objects.requireNonNull(key, "key is required"); + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + int openingBrace = -1; + int closingBrace = -1; + for (int index = 0; index < keyBytes.length; index++) { + if (keyBytes[index] == '{') { + openingBrace = index; + break; + } + } + if (openingBrace >= 0) { + for (int index = openingBrace + 1; index < keyBytes.length; index++) { + if (keyBytes[index] == '}') { + closingBrace = index; + break; + } + } + } + + byte[] hashInput = keyBytes; + int offset = 0; + int length = keyBytes.length; + if (openingBrace >= 0 && closingBrace > openingBrace + 1) { + offset = openingBrace + 1; + length = closingBrace - openingBrace - 1; + } + int crc = crc16(hashInput, offset, length); + return crc % REDIS_CLUSTER_SLOT_COUNT; + } + + private static void rejectOverlappingOwnership(List declarations) { + for (int leftIndex = 0; leftIndex < declarations.size(); leftIndex++) { + PrefixDeclaration left = declarations.get(leftIndex); + for (int rightIndex = leftIndex + 1; rightIndex < declarations.size(); rightIndex++) { + PrefixDeclaration right = declarations.get(rightIndex); + boolean overlaps = + left.prefix().startsWith(right.prefix()) || right.prefix().startsWith(left.prefix()); + boolean samePrincipalScope = + left.owner().equals(right.owner()) + && left.role() == right.role() + && left.principal().equals(right.principal()); + if (overlaps && !samePrincipalScope) { + throw new IllegalArgumentException( + "overlapping Redis prefixes have conflicting ownership: " + + left.prefix() + + " and " + + right.prefix()); + } + } + } + } + + private static void validateDeclaredOwnership( + RedisScriptDescriptor descriptor, Map prefixDeclarations) { + for (RedisScriptDescriptor.KeySpec key : descriptor.keys()) { + PrefixDeclaration declaration = prefixDeclarations.get(key.ownedPrefix()); + if (declaration == null) { + throw new IllegalArgumentException( + "script " + + descriptor.scriptId() + + " references an unowned prefix: " + + key.ownedPrefix()); + } + if (!declaration.owner().equals(descriptor.owner()) + || declaration.role() != descriptor.role() + || !declaration.principal().equals(descriptor.principal())) { + throw new IllegalArgumentException( + "script " + descriptor.scriptId() + " has a wrong owner, principal, or Redis role"); + } + } + } + + private static String extractHashTag(String key) { + int openingBrace = key.indexOf('{'); + if (openingBrace < 0) { + return null; + } + int closingBrace = key.indexOf('}', openingBrace + 1); + int nestedOpeningBrace = key.indexOf('{', openingBrace + 1); + if (closingBrace <= openingBrace + 1 + || (nestedOpeningBrace >= 0 && nestedOpeningBrace < closingBrace)) { + return null; + } + return key.substring(openingBrace + 1, closingBrace); + } + + private static int crc16(byte[] bytes, int offset, int length) { + int crc = 0; + for (int index = offset; index < offset + length; index++) { + crc ^= (bytes[index] & 0xff) << 8; + for (int bit = 0; bit < 8; bit++) { + crc = (crc & 0x8000) == 0 ? crc << 1 : (crc << 1) ^ 0x1021; + } + crc &= 0xffff; + } + return crc; + } + + private static boolean containsControlCharacter(String value) { + return value.chars().anyMatch(Character::isISOControl); + } + + private static void requireEquals(Object expected, Object actual, String fieldName) { + if (!Objects.equals(expected, actual)) { + throw new IllegalArgumentException( + "invocation " + fieldName + " does not match its registration"); + } + } + + public record PrefixDeclaration( + String owner, RedisScriptDescriptor.RedisRole role, String principal, String prefix) { + public PrefixDeclaration { + Objects.requireNonNull(role, "prefix Redis role is required"); + if (owner == null || !owner.matches("[a-z][a-z0-9-]*")) { + throw new IllegalArgumentException("prefix owner must be a lowercase service identifier"); + } + if (principal == null || !principal.matches("[a-z][a-z0-9_]*")) { + throw new IllegalArgumentException("prefix principal must be a lowercase Redis principal"); + } + if (prefix == null || !prefix.matches("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:")) { + throw new IllegalArgumentException("prefix must be colon-delimited and end with a colon"); + } + } + } + + /** The supplied identity and exact KEYS/ARGV values to validate before any Redis call. */ + public record InvocationRequest( + String scriptId, + String resourcePath, + String sha256, + String owner, + String principal, + RedisScriptDescriptor.RedisRole role, + List keys, + List arguments) { + public InvocationRequest { + keys = immutableValues(keys, "KEYS values are required"); + arguments = immutableValues(arguments, "ARGV values are required"); + } + + public List keys() { + return List.copyOf(keys); + } + + public List arguments() { + return List.copyOf(arguments); + } + + private static List immutableValues(List values, String message) { + if (values == null) { + throw new IllegalArgumentException(message); + } + return List.copyOf(values); + } + } +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java new file mode 100644 index 0000000000..9e60213b29 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.List; +import java.util.OptionalInt; + +/** Immutable proof that an invocation matched one registered Redis script contract. */ +public final class RedisInvocationContract { + + private final RedisScriptDescriptor descriptor; + private final List keys; + private final List arguments; + private final Integer clusterSlot; + + RedisInvocationContract( + RedisScriptDescriptor descriptor, + List keys, + List arguments, + Integer clusterSlot) { + this.descriptor = descriptor; + this.keys = List.copyOf(keys); + this.arguments = List.copyOf(arguments); + this.clusterSlot = clusterSlot; + } + + public RedisScriptDescriptor descriptor() { + return descriptor; + } + + public List keys() { + return keys; + } + + public List arguments() { + return arguments; + } + + /** Empty when no KEYS entry declared a hash tag. */ + public OptionalInt clusterSlot() { + return clusterSlot == null ? OptionalInt.empty() : OptionalInt.of(clusterSlot); + } +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java new file mode 100644 index 0000000000..f7203482ba --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** Immutable declaration of one versioned, owner-executed Redis script contract. */ +public record RedisScriptDescriptor( + String scriptId, + String resourcePath, + String sha256, + String owner, + String principal, + RedisRole role, + List keys, + List arguments, + ScriptCategory category, + List outcomes, + ResetSensitivity resetSensitivity, + LossClass lossClass, + String tailLossBehavior, + CompatibilityLevel compatibilityLevel, + List supportedCoexistence, + String legacyPayloadShape) { + + public static final String NO_PAYLOAD_VERSION = "none"; + public static final String LEGACY_PAYLOAD_VERSION = "legacy"; + + private static final Pattern SCRIPT_ID_PATTERN = + Pattern.compile("[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*\\.v[1-9][0-9]*"); + private static final Pattern RESOURCE_PATH_PATTERN = + Pattern.compile("redis/(?:[a-z0-9][a-z0-9_-]*/)*[a-z0-9][a-z0-9_-]*\\.lua"); + private static final Pattern OWNER_PATTERN = Pattern.compile("[a-z][a-z0-9-]*"); + private static final Pattern PRINCIPAL_PATTERN = Pattern.compile("[a-z][a-z0-9_]*"); + private static final Pattern PREFIX_PATTERN = + Pattern.compile("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:"); + private static final Pattern DECLARATION_NAME_PATTERN = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern OUTCOME_CODE_PATTERN = Pattern.compile("[A-Z][A-Z0-9_]*"); + private static final Pattern VERSION_PATTERN = Pattern.compile("v[1-9][0-9]*"); + + public RedisScriptDescriptor { + requireMatch(scriptId, SCRIPT_ID_PATTERN, "scriptId must be a supported versioned identifier"); + requireMatch( + resourcePath, + RESOURCE_PATH_PATTERN, + "resourcePath must be a relative redis/ classpath Lua resource path"); + requireMatch(sha256, Pattern.compile("[0-9a-f]{64}"), "sha256 must be 64 lowercase hex digits"); + requireMatch(owner, OWNER_PATTERN, "owner must be a lowercase service identifier"); + requireMatch(principal, PRINCIPAL_PATTERN, "principal must be a lowercase Redis principal"); + Objects.requireNonNull(role, "role is required"); + Objects.requireNonNull(category, "category is required"); + Objects.requireNonNull(resetSensitivity, "resetSensitivity is required"); + Objects.requireNonNull(lossClass, "lossClass is required"); + Objects.requireNonNull(compatibilityLevel, "compatibilityLevel is required"); + + keys = immutableNonEmpty(keys, "KEYS declarations are required"); + arguments = + immutable(arguments, "ARGV declarations are required, including an explicit empty list"); + outcomes = immutableNonEmpty(outcomes, "outcomes are required"); + supportedCoexistence = + immutableNonEmpty( + supportedCoexistence, "supported caller/payload coexistence metadata is required"); + tailLossBehavior = requireDescription(tailLossBehavior, "tailLossBehavior"); + legacyPayloadShape = optionalDescription(legacyPayloadShape, "legacyPayloadShape"); + + Set keyNames = new HashSet<>(); + for (KeySpec key : keys) { + if (!keyNames.add(key.name())) { + throw new IllegalArgumentException("duplicate KEYS declaration name: " + key.name()); + } + } + + Set argumentNames = new HashSet<>(); + for (ArgumentSpec argument : arguments) { + if (!argumentNames.add(argument.name())) { + throw new IllegalArgumentException("duplicate ARGV declaration name: " + argument.name()); + } + } + + Set outcomeCodes = new HashSet<>(); + for (OutcomeSpec outcome : outcomes) { + if (!outcomeCodes.add(outcome.code())) { + throw new IllegalArgumentException("duplicate outcome code: " + outcome.code()); + } + } + + Set combinations = new HashSet<>(); + boolean supportsLegacyPayload = false; + for (SupportedCoexistence combination : supportedCoexistence) { + if (!combinations.add(combination)) { + throw new IllegalArgumentException("duplicate caller/payload coexistence declaration"); + } + supportsLegacyPayload |= combination.payloadVersion().equals(LEGACY_PAYLOAD_VERSION); + } + if (supportsLegacyPayload && legacyPayloadShape == null) { + throw new IllegalArgumentException( + "legacyPayloadShape is required when a versionless payload is supported"); + } + if (!supportsLegacyPayload && legacyPayloadShape != null) { + throw new IllegalArgumentException( + "legacyPayloadShape is only valid when a legacy payload is supported"); + } + + if (keys.size() > 1 + && keys.stream().anyMatch(key -> key.hashTagDeclaration() != HashTagDeclaration.REQUIRED)) { + throw new IllegalArgumentException( + "every KEYS declaration in a multi-key script must require a hash tag"); + } + } + + public List keys() { + return List.copyOf(keys); + } + + public List arguments() { + return List.copyOf(arguments); + } + + public List outcomes() { + return List.copyOf(outcomes); + } + + public List supportedCoexistence() { + return List.copyOf(supportedCoexistence); + } + + public enum RedisRole { + COORDINATION, + CACHE_RATE_LIMIT + } + + public enum HashTagDeclaration { + NOT_REQUIRED, + REQUIRED + } + + public enum ScriptCategory { + TICK_LOCK, + TIMER_QUEUE, + SESSION_CAS, + SESSION_TO_REGION_BRIDGE, + MAINTENANCE, + CACHE, + RATE_LIMIT + } + + public enum OutcomeCategory { + SUCCESS, + REPLAY, + STALE, + VALIDATION_FAILURE, + CONTENTION, + DEFERRAL + } + + public enum MutationEffect { + MUTATING, + NON_MUTATING + } + + public enum ResetSensitivity { + NONE, + SESSION, + REGION, + TENANT, + CLUSTER + } + + /** Work classes from ADR 0058. */ + public enum LossClass { + ACCEPTED_PLAYER_COMMAND, + STAGED_EFFECT_OR_RETRY, + CORRECTNESS_BEARING_TIMER, + LOSSY_TIMER_OR_ADVISORY_HINT, + SESSION_LEASE_CACHE_OR_WAKE_UP, + PREMIUM_FINANCIAL_CROSS_TENANT_OR_UNIQUE_EXTERNAL_EFFECT, + EMPTY_REDIS_COLD_START_OR_RESET + } + + public enum CompatibilityLevel { + COMPATIBLE, + REQUIRES_REGION_RESET, + REQUIRES_TENANT_RESET, + REQUIRES_CLUSTER_RESET + } + + public record KeySpec(String name, String ownedPrefix, HashTagDeclaration hashTagDeclaration) { + public KeySpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "KEYS name must be a supported identifier"); + requireMatch(ownedPrefix, PREFIX_PATTERN, "ownedPrefix must be a colon-delimited key prefix"); + Objects.requireNonNull(hashTagDeclaration, "hashTagDeclaration is required"); + } + } + + public record ArgumentSpec(String name) { + public ArgumentSpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "ARGV name must be a supported identifier"); + } + } + + public record OutcomeSpec(String code, OutcomeCategory category, MutationEffect effect) { + public OutcomeSpec { + requireMatch(code, OUTCOME_CODE_PATTERN, "outcome code must be uppercase and stable"); + Objects.requireNonNull(category, "outcome category is required"); + Objects.requireNonNull(effect, "outcome mutation effect is required"); + if (category != OutcomeCategory.SUCCESS && effect != MutationEffect.NON_MUTATING) { + throw new IllegalArgumentException( + "replay, stale, validation, contention, and deferral outcomes must be non-mutating"); + } + } + } + + /** A caller version and payload version that may coexist for this script version. */ + public record SupportedCoexistence(String callerVersion, String payloadVersion) { + public SupportedCoexistence { + requireMatch(callerVersion, VERSION_PATTERN, "callerVersion must use vN syntax"); + if (!NO_PAYLOAD_VERSION.equals(payloadVersion) + && !LEGACY_PAYLOAD_VERSION.equals(payloadVersion)) { + requireMatch( + payloadVersion, VERSION_PATTERN, "payloadVersion must use vN, none, or legacy"); + } + } + } + + private static void requireMatch(String value, Pattern pattern, String message) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(message); + } + } + + private static String requireDescription(String value, String fieldName) { + if (value == null || value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " is required and must be trimmed"); + } + return value; + } + + private static String optionalDescription(String value, String fieldName) { + if (value == null || value.isBlank()) { + return null; + } + if (!value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " must be trimmed"); + } + return value; + } + + private static List immutable(List values, String message) { + if (values == null) { + throw new IllegalArgumentException(message); + } + return List.copyOf(values); + } + + private static List immutableNonEmpty(List values, String message) { + List copy = immutable(values, message); + if (copy.isEmpty()) { + throw new IllegalArgumentException(message); + } + return copy; + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java new file mode 100644 index 0000000000..30fe3b8265 --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java @@ -0,0 +1,444 @@ +package net.firedevops.firemud.common.redis.contracts; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class RedisContractRegistryTest { + + private static final String ISSUER_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final String ISSUER_KEY = ISSUER_PREFIX + "current"; + private static final RedisScriptDescriptor ISSUER_DESCRIPTOR = issuerDescriptor(); + + @Test + void preparesRegisteredSingleKeyInvocation() { + RedisInvocationContract invocation = issuerRegistry().prepareInvocation(issuerRequest()); + + assertEquals(ISSUER_DESCRIPTOR, invocation.descriptor()); + assertEquals(List.of(ISSUER_KEY), invocation.keys()); + assertEquals(List.of("12", "13"), invocation.arguments()); + assertTrue(invocation.clusterSlot().isEmpty()); + } + + @Test + void preparesTaggedMultiKeyInvocationAndReportsClusterSlot() { + RedisScriptDescriptor descriptor = tickDescriptor(); + RedisContractRegistry registry = + new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", "tick:")), List.of(descriptor)); + RedisContractRegistry.InvocationRequest request = + new RedisContractRegistry.InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of("tick:{region-one}:lease", "tick:{region-one}:meta"), + List.of("41")); + + RedisInvocationContract invocation = registry.prepareInvocation(request); + + assertEquals( + RedisContractRegistry.clusterSlot("tick:{region-one}:lease"), + invocation.clusterSlot().orElseThrow()); + assertEquals( + invocation.clusterSlot(), + java.util.OptionalInt.of(RedisContractRegistry.clusterSlot("tick:{region-one}:meta"))); + } + + @Test + void clusterSlotUsesRedisCrc16XmodemKnownVector() { + assertEquals(12739, RedisContractRegistry.clusterSlot("key{123456789}")); + } + + @Test + void rejectsWrongRedisRole() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.CACHE_RATE_LIMIT, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")))); + } + + @Test + void rejectsWrongOwner() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "account", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")))); + } + + @Test + void rejectsWrongPrincipal() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "game-session", + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")))); + } + + @Test + void rejectsWrongDigestAndResourcePath() { + assertThrows( + IllegalArgumentException.class, + () -> { + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + issuerRegistry() + .prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + "b".repeat(64), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments())); + }); + assertThrows( + IllegalArgumentException.class, + () -> { + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + issuerRegistry() + .prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + "redis/auth/other.lua", + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments())); + }); + } + + @Test + void rejectsUnknownScriptIdentity() { + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + new RedisContractRegistry.InvocationRequest( + "game-session.issuer-generation.v2", + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments()))); + } + + @Test + void rejectsUnownedKeyPrefix() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + "session:game:auth:another-family:key", + List.of("12", "13")))); + } + + @Test + void rejectsMissingAndMalformedRequiredHashTags() { + RedisContractRegistry registry = tickRegistry(); + assertThrows( + IllegalArgumentException.class, + () -> registry.prepareInvocation(tickRequest("tick:lease", "tick:meta"))); + assertThrows( + IllegalArgumentException.class, + () -> registry.prepareInvocation(tickRequest("tick:{}:lease", "tick:{}:meta"))); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + tickRequest("tick:{region-one:lease", "tick:{region-one:meta"))); + assertThrows( + IllegalArgumentException.class, + () -> registry.prepareInvocation(tickRequest("tick:{{scope}:lease", "tick:{{scope}:meta"))); + } + + @Test + void rejectsMultiKeyCrossSlotInvocation() { + RedisContractRegistry registry = tickRegistry(); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + tickRequest("tick:{region-one}:lease", "tick:{region-two}:meta"))); + } + + @Test + void rejectsKeysAndArgumentsArityMismatch() { + RedisContractRegistry registry = issuerRegistry(); + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + List.of(), + valid.arguments()))); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + List.of("12")))); + } + + @Test + void rejectsDuplicateAndConflictingPrefixOwnership() { + RedisContractRegistry.PrefixDeclaration declaration = + prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisContractRegistry( + List.of(declaration, declaration), List.of(ISSUER_DESCRIPTOR))); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisContractRegistry( + List.of(declaration, prefix("account", "account_coord_app", "session:game:auth:")), + List.of(ISSUER_DESCRIPTOR))); + } + + @Test + void rejectsDescriptorWhoseOwnerPrincipalOrRoleDoesNotOwnItsPrefix() { + RedisScriptDescriptor wrongOwner = + descriptor( + "game-session.issuer-generation.v1", + "redis/auth/issuer_generation.lua", + "a".repeat(64), + "account", + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + ISSUER_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of("expectedGeneration", "nextGeneration"), + "tail-loss behavior is explicit"); + + assertThrows( + IllegalArgumentException.class, + () -> + new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX)), + List.of(wrongOwner))); + } + + @Test + void defensivelyCopiesInvocationInputs() { + RedisContractRegistry registry = issuerRegistry(); + List keys = new ArrayList<>(List.of(ISSUER_KEY)); + List arguments = new ArrayList<>(List.of("12", "13")); + RedisContractRegistry.InvocationRequest request = + new RedisContractRegistry.InvocationRequest( + ISSUER_DESCRIPTOR.scriptId(), + ISSUER_DESCRIPTOR.resourcePath(), + ISSUER_DESCRIPTOR.sha256(), + ISSUER_DESCRIPTOR.owner(), + ISSUER_DESCRIPTOR.principal(), + ISSUER_DESCRIPTOR.role(), + keys, + arguments); + keys.clear(); + arguments.clear(); + + assertEquals(List.of(ISSUER_KEY), request.keys()); + assertEquals(List.of("12", "13"), request.arguments()); + assertThrows(UnsupportedOperationException.class, () -> request.keys().add("other")); + assertThrows(UnsupportedOperationException.class, () -> request.arguments().add("14")); + + RedisInvocationContract invocation = registry.prepareInvocation(request); + + assertEquals(List.of(ISSUER_KEY), invocation.keys()); + assertEquals(List.of("12", "13"), invocation.arguments()); + assertThrows(UnsupportedOperationException.class, () -> invocation.keys().add("other")); + assertFalse(invocation.clusterSlot().isPresent()); + } + + private static RedisContractRegistry issuerRegistry() { + return new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX)), + List.of(ISSUER_DESCRIPTOR)); + } + + private static RedisContractRegistry tickRegistry() { + return new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", "tick:")), + List.of(tickDescriptor())); + } + + private static RedisContractRegistry.InvocationRequest issuerRequest() { + return request( + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")); + } + + private static RedisContractRegistry.InvocationRequest request( + String owner, + String principal, + RedisScriptDescriptor.RedisRole role, + String digest, + String key, + List arguments) { + return new RedisContractRegistry.InvocationRequest( + ISSUER_DESCRIPTOR.scriptId(), + ISSUER_DESCRIPTOR.resourcePath(), + digest, + owner, + principal, + role, + List.of(key), + arguments); + } + + private static RedisContractRegistry.InvocationRequest tickRequest( + String firstKey, String secondKey) { + RedisScriptDescriptor descriptor = tickDescriptor(); + return new RedisContractRegistry.InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of(firstKey, secondKey), + List.of("41")); + } + + private static RedisContractRegistry.PrefixDeclaration prefix( + String owner, String principal, String prefix) { + return new RedisContractRegistry.PrefixDeclaration( + owner, RedisScriptDescriptor.RedisRole.COORDINATION, principal, prefix); + } + + private static RedisScriptDescriptor issuerDescriptor() { + return descriptor( + "game-session.issuer-generation.v1", + "redis/auth/issuer_generation_cas.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerGeneration", + ISSUER_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of("expectedGeneration", "nextGeneration"), + "loss closes the issuer scope until authenticated Account reconciliation"); + } + + private static RedisScriptDescriptor tickDescriptor() { + return descriptor( + "game-session.tick-stage.v1", + "redis/tick_stage.lua", + "c".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "lease", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "metadata", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)), + List.of("expectedEpoch"), + "lost staged work remains subject to its durable ledger and owner reconciliation"); + } + + private static RedisScriptDescriptor descriptor( + String scriptId, + String resourcePath, + String digest, + String owner, + String principal, + RedisScriptDescriptor.RedisRole role, + List keys, + List argumentNames, + String tailLossBehavior) { + return new RedisScriptDescriptor( + scriptId, + resourcePath, + digest, + owner, + principal, + role, + keys, + argumentNames.stream().map(RedisScriptDescriptor.ArgumentSpec::new).toList(), + RedisScriptDescriptor.ScriptCategory.SESSION_CAS, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "UPDATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "STALE_GENERATION", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + tailLossBehavior, + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none")), + null); + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java new file mode 100644 index 0000000000..f06f974337 --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java @@ -0,0 +1,229 @@ +package net.firedevops.firemud.common.redis.contracts; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class RedisScriptDescriptorTest { + + @Test + void requiresScriptIdentityResourceDigestAndAllMetadata() { + assertThrows( + IllegalArgumentException.class, + () -> descriptor("game-session.issuer.v1", "../issuer.lua", "a".repeat(64))); + assertThrows( + IllegalArgumentException.class, + () -> descriptor("issuer", "redis/issuer.lua", "a".repeat(64))); + assertThrows( + IllegalArgumentException.class, + () -> descriptor("game-session.issuer.v1", "redis/issuer.lua", "bad-digest")); + assertThrows( + IllegalArgumentException.class, + () -> descriptor("game-session.issuer.v1", "redis/issuer.lua", "a".repeat(64), " ")); + } + + @Test + void rejectsDuplicateKeyAndArgumentDeclarations() { + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED), + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(new RedisScriptDescriptor.ArgumentSpec("expected")), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of( + new RedisScriptDescriptor.ArgumentSpec("expected"), + new RedisScriptDescriptor.ArgumentSpec("expected")), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null)); + } + + @Test + void requiresOutcomesAndCallerPayloadCoexistence() { + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + List.of(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + List.of(), + null)); + } + + @Test + void requiresExplicitLegacyPayloadShapeAndNonMutatingFailureOutcomes() { + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "legacy")), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.MUTATING)); + } + + @Test + void descriptorListAccessorsRemainImmutable() { + RedisScriptDescriptor descriptor = + descriptor("game-session.issuer.v1", "redis/issuer.lua", "a".repeat(64)); + + assertThrows(UnsupportedOperationException.class, () -> descriptor.keys().clear()); + assertThrows(UnsupportedOperationException.class, () -> descriptor.arguments().clear()); + assertThrows(UnsupportedOperationException.class, () -> descriptor.outcomes().clear()); + assertThrows( + UnsupportedOperationException.class, () -> descriptor.supportedCoexistence().clear()); + } + + private static RedisScriptDescriptor descriptor(String id, String path, String digest) { + return descriptor(id, path, digest, "loss behavior is explicit"); + } + + private static RedisScriptDescriptor descriptor( + String id, String path, String digest, String tailLoss) { + return new RedisScriptDescriptor( + id, + path, + digest, + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", "session:auth:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + tailLoss, + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null); + } + + private static RedisScriptDescriptor.ScriptCategory category() { + return RedisScriptDescriptor.ScriptCategory.SESSION_CAS; + } + + private static List outcomes() { + return List.of( + new RedisScriptDescriptor.OutcomeSpec( + "UPDATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)); + } + + private static RedisScriptDescriptor.LossClass lossClass() { + return RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP; + } + + private static List coexistence() { + return List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none")); + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java index 926dee9c20..36215a143a 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Optional; import java.util.TreeSet; +import java.util.UUID; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.grpc.GrpcAppErrors; @@ -56,10 +57,10 @@ public SendCommunicationResponse send(SendCommunicationRequest request) { SendCommunicationResponse.newBuilder() .setType(request.getType()) .setMessage(normalizedText); - String validatedAccountId = parsePositiveAccountId(request.getAccountId()); + String validatedAccountId = parseCanonicalAccountId(request.getAccountId()); if (validatedAccountId == null) { return errorResponse( - builder, "INVALID_ARGUMENT", "account_id must be a positive numeric account id"); + builder, "INVALID_ARGUMENT", "account_id must be a canonical non-nil UUID"); } if (tenantId != null && !isSocialCapabilityEnabled(tenantId, gameInstanceId)) { @@ -396,15 +397,17 @@ private Long parseTenantId(String tenantId) { } } - private String parsePositiveAccountId(String accountId) { - if (!StringUtils.hasText(accountId)) { + private String parseCanonicalAccountId(String accountId) { + if (accountId == null || accountId.isBlank()) { return null; } - String normalized = accountId.trim(); try { - long parsed = Long.parseLong(normalized); - return parsed > 0L ? Long.toString(parsed) : null; - } catch (NumberFormatException ignored) { + UUID parsed = UUID.fromString(accountId); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(accountId)) { + return null; + } + return accountId; + } catch (IllegalArgumentException ignored) { return null; } } diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java index 5091a32be2..3653635684 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java @@ -41,7 +41,7 @@ @ExtendWith(MockitoExtension.class) class CommunicationAggregationServiceTest { - private static final String VALID_ACCOUNT_ID = "42"; + private static final String VALID_ACCOUNT_ID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; @Mock private SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialStub; @@ -125,14 +125,16 @@ void unavailableSocialCapabilityAuthorityFailsClosedWithoutCallingDownstreamServ } @Test - void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { + void rejectsMissingMalformedNonCanonicalAndNilAccountIdsBeforeDownstreamCalls() { for (String[] accountIdCase : new String[][] { {"empty", ""}, {"whitespace-only", " "}, {"malformed", "not-a-number"}, - {"zero", "0"}, - {"negative", "-1"}, + {"numeric", "42"}, + {"nil", "00000000-0000-0000-0000-000000000000"}, + {"uppercase", "C91FB96E-5AD8-4E4E-A12D-2838640093B2"}, + {"padded", " " + VALID_ACCOUNT_ID + " "}, }) { String accountIdCaseDescription = accountIdCase[0]; String accountId = accountIdCase[1]; @@ -154,7 +156,7 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { .isEqualTo("INVALID_ARGUMENT"); assertThat(resp.getError().getMessage()) .as(accountIdCaseDescription) - .isEqualTo("account_id must be a positive numeric account id"); + .isEqualTo("account_id must be a canonical non-nil UUID"); } verify(entityStub, never()).listRoomEntities(any()); @@ -162,7 +164,7 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { } @Test - void normalizesPaddedNoncanonicalAccountIdForSocialSender() { + void preservesCanonicalAccountUuidForSocialSenderWithoutCharacterFallback() { when(socialStub.sendMessage(any())) .thenReturn(SendMessageResponse.newBuilder().setSuccess(true).build()); @@ -172,7 +174,7 @@ void normalizesPaddedNoncanonicalAccountIdForSocialSender() { .setTenantId("tenant-1") .setSessionId("sess-1") .setCharacterId("player-0") - .setAccountId(" 0042 ") + .setAccountId(VALID_ACCOUNT_ID) .setType(CommunicationType.TELL) .setTargetCharacterId("player-9") .setTargetCharacterName("Sora") @@ -182,7 +184,7 @@ void normalizesPaddedNoncanonicalAccountIdForSocialSender() { assertThat(resp.getSuccess()).isTrue(); ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); verify(socialStub).sendMessage(captor.capture()); - assertThat(captor.getValue().getSenderId()).isEqualTo("42"); + assertThat(captor.getValue().getSenderId()).isEqualTo(VALID_ACCOUNT_ID); } @Test diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 81a8bd7842..73b780434a 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -50,6 +50,7 @@ dependencies { implementation(libs.spring.boot.starter.websocket) implementation(project(":common-saga")) implementation(project(":common-security")) + implementation(project(":common-redis-contracts")) implementation(libs.jjwt.api) runtimeOnly(libs.jjwt.impl) runtimeOnly(libs.jjwt.jackson) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java new file mode 100644 index 0000000000..59bbf8210b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.PrefixDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; + +/** Registered single-key coordination contract for Game Session's issuer projection. */ +public final class IssuerAuthorityProjectionRedisContract { + public static final String SCRIPT_ID = "game-session.issuer-authority-projection.v1"; + public static final String RESOURCE_PATH = "redis/issuer_authority_projection_cas.lua"; + public static final String OWNER = "game-session-service"; + public static final String PRINCIPAL = "gamesession_coord_app"; + public static final RedisRole ROLE = RedisRole.COORDINATION; + public static final String PROJECTION_SCHEMA_VERSION = + IssuerAuthorityProjectionTransitions.SCHEMA_VERSION; + public static final String KEY_PREFIX = IssuerAuthorityProjectionTransitions.KEY_PREFIX; + + private static final String RESOURCE_SHA256 = + "1c1df7fdf6edc42a9e3ad5dfd5a0db7c33295b41a9e5c28df2a65e98d9069c16"; + private static final RedisScriptDescriptor DESCRIPTOR = createDescriptor(); + private static final RedisContractRegistry REGISTRY = + new RedisContractRegistry( + List.of(new PrefixDeclaration(OWNER, ROLE, PRINCIPAL, KEY_PREFIX)), List.of(DESCRIPTOR)); + + private IssuerAuthorityProjectionRedisContract() {} + + public static RedisScriptDescriptor descriptor() { + return DESCRIPTOR; + } + + /** Declarative registry only; executable access remains private to the typed owner store. */ + public static RedisContractRegistry registry() { + return REGISTRY; + } + + public static String keyForIssuer(String issuerId) { + Objects.requireNonNull(issuerId, "exact issuer ID is required"); + if (issuerId.isBlank() || issuerId.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException( + "exact issuer ID must be nonblank and contain no controls"); + } + return KEY_PREFIX + issuerId; + } + + static RedisInvocationContract prepareInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + return REGISTRY.prepareInvocation( + new InvocationRequest( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of(key), + List.of(expectedMode, expectedBytes, candidateBytes))); + } + + private static RedisScriptDescriptor createDescriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of(new KeySpec("issuerProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)), + List.of( + new ArgumentSpec("expectedMode"), + new ArgumentSpec("expectedBytes"), + new ArgumentSpec("candidateBytes")), + ScriptCategory.SESSION_CAS, + List.of( + new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), + new OutcomeSpec("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)), + ResetSensitivity.CLUSTER, + LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "On loss, quarantine this issuer scope until an authenticated exact Account checkpoint is reconciled; never admit from this projection.", + CompatibilityLevel.COMPATIBLE, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java new file mode 100644 index 0000000000..d55623afe1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java @@ -0,0 +1,610 @@ +package net.firedevops.firemud.gamesession.service; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +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.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceSnapshot; + +/** Pure decision layer for the derived Game Session issuer-authority projection. */ +public final class IssuerAuthorityProjectionTransitions { + public static final String KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + public static final String SCHEMA_VERSION = "game-session-auth-issuer-projection/v1"; + + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + private static final BigInteger ZERO = BigInteger.ZERO; + private static final BigInteger ONE = BigInteger.ONE; + + private static final Set BASE_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "lastAppliedSourceOutboxSequence", + "sourceOutboxStreamKey", + "appliedAt", + "appliedSourceEvidence"); + private static final Set POSITIVE_FIELDS = Set.of("sourceEventId", "sourceEventDigest"); + + private IssuerAuthorityProjectionTransitions() {} + + /** + * Creates an initial projection only from Account's complete authenticated current readback. + * Sequence zero is source absence evidence; it is not recipient admission evidence. + */ + public static Decision bootstrap(SourceReadback currentReadback, String appliedAt) { + try { + VerifiedReadback readback = verifyReadback(currentReadback); + if (readback.selectedEvent().isPresent()) { + return new Quarantine( + Optional.empty(), QuarantineReason.BOOTSTRAP_REQUIRES_CURRENT_READBACK); + } + requireAppliedAt(appliedAt); + return new Mutation( + Optional.empty(), projectionFor(readback.snapshot(), appliedAt), MutationKind.BOOTSTRAP); + } catch (EvidenceRejected rejected) { + return new Quarantine(Optional.empty(), rejected.reason()); + } catch (IllegalArgumentException malformed) { + return new Quarantine(Optional.empty(), QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } + + /** + * Decides whether one Account-authenticated selected source event advances, duplicates, or + * contradicts the observed projection. The expected fields and next projection are immutable + * compare-and-set evidence; this method performs no storage operation. + */ + public static Decision decide( + Map observedProjection, SourceReadback sourceReadback, String appliedAt) { + Optional> observed = immutableObserved(observedProjection); + final ExistingProjection existing; + try { + if (observedProjection == null) { + return new Quarantine(Optional.empty(), QuarantineReason.MISSING_EXISTING_PROJECTION); + } + existing = parseExistingProjection(observedProjection); + } catch (IllegalArgumentException malformed) { + return new Quarantine(observed, QuarantineReason.MALFORMED_EXISTING_PROJECTION); + } + + try { + VerifiedReadback readback = verifyReadback(sourceReadback); + if (readback.selectedEvent().isEmpty()) { + return new Quarantine(observed, QuarantineReason.SELECTED_EVENT_REQUIRED); + } + + Checkpoint current = readback.snapshot(); + IssuerGenerationAuthorityEvent selected = readback.selectedEvent().orElseThrow(); + if (!existing.issuerId().equals(current.issuerId()) + || !existing.streamKey().equals(current.streamKey())) { + return new Quarantine(observed, QuarantineReason.ISSUER_OR_STREAM_CHANGED); + } + if (current.sequence().compareTo(existing.sequence()) < 0 + || current.generation().compareTo(existing.generation()) < 0 + || current.sourceVersion().compareTo(existing.sourceVersion()) < 0) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); + } + if (current.sequence().equals(existing.sequence())) { + if (existing.latestEvent() == null) { + if (current.latestEvent() != null + || !current.generation().equals(ONE) + || !current.sourceVersion().equals(ONE)) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_CONFLICT); + } + } else if (current.latestEvent() == null + || !existing + .latestEvent() + .canonicalJson() + .equals(current.latestEvent().canonicalJson())) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_CONFLICT); + } + } else if (current.sourceVersion().compareTo(existing.sourceVersion()) <= 0) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); + } + + BigInteger selectedSequence = positiveDecimal(selected.outboxSequence(), "selected sequence"); + int order = selectedSequence.compareTo(existing.sequence()); + if (order < 0) { + if (positiveDecimal(selected.issuerAuthGeneration(), "selected generation") + .compareTo(existing.generation()) + > 0) { + return new Quarantine(observed, QuarantineReason.HISTORICAL_EVENT_PROGRESS_CONFLICT); + } + if (positiveDecimal(selected.sourceVersion(), "selected source version") + .compareTo(existing.sourceVersion()) + > 0) { + return new Quarantine(observed, QuarantineReason.HISTORICAL_EVENT_PROGRESS_CONFLICT); + } + // The selected event is an exact immutable Account lookup. Historical generations and + // source versions may be lower than the installed later projection. + return new NoOp(NoOpReason.VERIFIED_HISTORICAL_DUPLICATE); + } + + if (order == 0) { + if (existing.latestEvent() == null + || !existing.latestEvent().canonicalJson().equals(selected.canonicalJson())) { + return new Quarantine(observed, QuarantineReason.DUPLICATE_EVENT_CONFLICT); + } + return new NoOp(NoOpReason.EXACT_DUPLICATE); + } + + BigInteger expectedNextSequence = existing.sequence().add(ONE); + if (!selectedSequence.equals(expectedNextSequence)) { + return new Quarantine(observed, QuarantineReason.EVENT_SEQUENCE_GAP); + } + + BigInteger eventGeneration = + positiveDecimal(selected.issuerAuthGeneration(), "selected generation"); + BigInteger eventSourceVersion = + positiveDecimal(selected.sourceVersion(), "selected source version"); + if (eventGeneration.compareTo(existing.generation()) < 0) { + return new Quarantine(observed, QuarantineReason.EVENT_GENERATION_REGRESSED); + } + if (eventSourceVersion.compareTo(existing.sourceVersion()) <= 0) { + return new Quarantine(observed, QuarantineReason.EVENT_SOURCE_VERSION_REGRESSED); + } + requireAppliedAt(appliedAt); + + BigInteger nextGeneration = eventGeneration.max(existing.generation()); + return new Mutation( + observed, + projectionFor( + selected, nextGeneration.toString(), selectedSequence.toString(), appliedAt), + MutationKind.ADVANCE); + } catch (EvidenceRejected rejected) { + return new Quarantine(observed, rejected.reason()); + } catch (IllegalArgumentException malformed) { + return new Quarantine(observed, QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } + + private static VerifiedReadback verifyReadback(SourceReadback readback) { + if (readback == null + || readback.requestId() == null + || readback.targetNamespace() == null + || readback.targetNamespace().isBlank() + || readback.sourceSnapshot() == null) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + UUID requestId; + try { + requestId = UUID.fromString(readback.requestId()); + } catch (IllegalArgumentException malformed) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (new UUID(0L, 0L).equals(requestId) || !requestId.toString().equals(readback.requestId())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + + Checkpoint snapshot = verifySnapshot(readback.sourceSnapshot()); + Optional selected = readback.requestedEvent(); + if (selected.isPresent()) { + IssuerGenerationAuthorityEvent event = verifyEvent(selected.orElseThrow()); + if (!sameSource(event, snapshot.issuerId(), snapshot.streamKey()) + || positiveDecimal(event.outboxSequence(), "selected sequence") + .compareTo(snapshot.sequence()) + > 0 + || positiveDecimal(event.issuerAuthGeneration(), "selected generation") + .compareTo(snapshot.generation()) + > 0 + || positiveDecimal(event.sourceVersion(), "selected source version") + .compareTo(snapshot.sourceVersion()) + > 0) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (snapshot.sequence().equals(positiveDecimal(event.outboxSequence(), "selected sequence")) + && (snapshot.latestEvent() == null + || !snapshot.latestEvent().canonicalJson().equals(event.canonicalJson()))) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } + return new VerifiedReadback(snapshot, selected); + } + + private static Checkpoint verifySnapshot(SourceSnapshot source) { + if (source == null || source.issuerId() == null || source.issuerId().isBlank()) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + String expectedScope = "issuer/" + source.issuerId(); + String expectedStream = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + expectedScope; + if (!expectedScope.equals(source.sourceScope()) + || !expectedStream.equals(source.outboxStreamKey())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + + BigInteger generation = positiveDecimal(source.issuerAuthGeneration(), "issuer generation"); + BigInteger sourceVersion = positiveDecimal(source.sourceVersion(), "source version"); + BigInteger sequence = nonnegativeDecimal(source.outboxSequence(), "outbox sequence"); + IssuerGenerationAuthorityEvent latest = + source.latestEvent().map(IssuerAuthorityProjectionTransitions::verifyEvent).orElse(null); + if (sequence.equals(ZERO)) { + if (!generation.equals(ONE) || !sourceVersion.equals(ONE) || latest != null) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } else if (latest == null + || !sameSource(latest, source.issuerId(), source.outboxStreamKey()) + || !sequence.equals(positiveDecimal(latest.outboxSequence(), "latest event sequence")) + || !generation.equals( + positiveDecimal(latest.issuerAuthGeneration(), "latest event generation")) + || !sourceVersion.equals( + positiveDecimal(latest.sourceVersion(), "latest event source version"))) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + return new Checkpoint( + source.issuerId(), source.outboxStreamKey(), generation, sourceVersion, sequence, latest); + } + + private static IssuerGenerationAuthorityEvent verifyEvent( + IssuerGenerationAuthorityEvent supplied) { + if (supplied == null) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + IssuerGenerationAuthorityEvent verified; + try { + verified = IssuerGenerationAuthorityEventV1Codec.verify(supplied.canonicalJson()); + } catch (IllegalArgumentException malformed) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (!verified.canonicalJson().equals(supplied.canonicalJson()) + || !verified.eventId().equals(supplied.eventId()) + || !verified.eventDigest().equals(supplied.eventDigest()) + || !verified.issuerId().equals(supplied.issuerId()) + || !verified.sourceScope().equals(supplied.sourceScope()) + || !verified.outboxStreamKey().equals(supplied.outboxStreamKey()) + || !verified.outboxSequence().equals(supplied.outboxSequence()) + || !verified.issuerAuthGeneration().equals(supplied.issuerAuthGeneration()) + || !verified.sourceVersion().equals(supplied.sourceVersion())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + UUID eventRequestId; + try { + eventRequestId = UUID.fromString(verified.requestId()); + } catch (IllegalArgumentException malformed) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (new UUID(0L, 0L).equals(eventRequestId) + || !eventRequestId.toString().equals(verified.requestId()) + || !(EVENT_ID_PREFIX + verified.requestId()).equals(verified.eventId())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + return verified; + } + + private static boolean sameSource( + IssuerGenerationAuthorityEvent event, String issuerId, String streamKey) { + return issuerId.equals(event.issuerId()) + && ("issuer/" + issuerId).equals(event.sourceScope()) + && streamKey.equals(event.outboxStreamKey()); + } + + private static Map projectionFor(Checkpoint checkpoint, String appliedAt) { + if (checkpoint.sequence().equals(ZERO)) { + return projectionMap( + checkpoint.issuerId(), + checkpoint.generation().toString(), + "0", + checkpoint.streamKey(), + null, + appliedAt, + Map.of()); + } + return projectionFor( + checkpoint.latestEvent(), + checkpoint.generation().toString(), + checkpoint.sequence().toString(), + appliedAt); + } + + private static Map projectionFor( + IssuerGenerationAuthorityEvent event, + String issuerGeneration, + String sequence, + String appliedAt) { + return projectionMap( + event.issuerId(), + issuerGeneration, + sequence, + event.outboxStreamKey(), + event, + appliedAt, + Map.of(sequence, event.canonicalJson())); + } + + private static Map projectionMap( + String issuerId, + String issuerGeneration, + String sequence, + String streamKey, + IssuerGenerationAuthorityEvent latestEvent, + String appliedAt, + Map appliedSourceEvidence) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", SCHEMA_VERSION); + fields.put("issuerId", issuerId); + fields.put("issuerAuthGeneration", issuerGeneration); + fields.put("lastAppliedSourceOutboxSequence", sequence); + fields.put("sourceOutboxStreamKey", streamKey); + if (latestEvent != null) { + fields.put("sourceEventId", latestEvent.eventId()); + fields.put("sourceEventDigest", latestEvent.eventDigest()); + } + fields.put("appliedAt", appliedAt); + fields.put("appliedSourceEvidence", appliedSourceEvidence); + return immutableMap(fields); + } + + private static ExistingProjection parseExistingProjection(Map supplied) { + if (supplied == null) { + throw new IllegalArgumentException("projection is absent"); + } + String schema = requiredString(supplied, "schemaVersion"); + String issuer = requiredString(supplied, "issuerId"); + String generationText = requiredString(supplied, "issuerAuthGeneration"); + String sequenceText = requiredString(supplied, "lastAppliedSourceOutboxSequence"); + String stream = requiredString(supplied, "sourceOutboxStreamKey"); + String appliedAt = requiredString(supplied, "appliedAt"); + if (!SCHEMA_VERSION.equals(schema) || issuer.isBlank() || appliedAt.isBlank()) { + throw new IllegalArgumentException("projection identity or schema is malformed"); + } + + BigInteger generation = positiveDecimal(generationText, "projection generation"); + BigInteger sequence = nonnegativeDecimal(sequenceText, "projection sequence"); + String expectedStream = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuer; + if (!expectedStream.equals(stream)) { + throw new IllegalArgumentException("projection stream identity is malformed"); + } + + Set expectedFields = new java.util.HashSet<>(BASE_FIELDS); + IssuerGenerationAuthorityEvent latest = null; + BigInteger sourceVersion = ONE; + Object evidenceValue = supplied.get("appliedSourceEvidence"); + if (!(evidenceValue instanceof Map evidence)) { + throw new IllegalArgumentException("projection source evidence is malformed"); + } + if (sequence.equals(ZERO)) { + if (!generation.equals(ONE) || !evidence.isEmpty()) { + throw new IllegalArgumentException("zero checkpoint projection is contradictory"); + } + } else { + expectedFields.addAll(POSITIVE_FIELDS); + if (evidence.size() != 1) { + throw new IllegalArgumentException("projection must retain its current source checkpoint"); + } + Object canonicalValue = evidence.get(sequenceText); + if (!(canonicalValue instanceof String canonicalEvent)) { + throw new IllegalArgumentException("projection current source evidence is absent"); + } + latest = verifiedProjectionEvent(canonicalEvent); + if (!sameSource(latest, issuer, stream) + || !sequence.equals(positiveDecimal(latest.outboxSequence(), "projection event sequence")) + || !generation.equals( + positiveDecimal(latest.issuerAuthGeneration(), "projection event generation")) + || !requiredString(supplied, "sourceEventId").equals(latest.eventId()) + || !requiredString(supplied, "sourceEventDigest").equals(latest.eventDigest())) { + throw new IllegalArgumentException("projection event does not match its checkpoint"); + } + sourceVersion = positiveDecimal(latest.sourceVersion(), "projection event source version"); + } + if (!supplied.keySet().equals(expectedFields)) { + throw new IllegalArgumentException("projection fields do not match the declared schema"); + } + validateEvidenceMapKeys(evidence, sequence, sequenceText); + return new ExistingProjection(issuer, generation, sourceVersion, sequence, stream, latest); + } + + private static IssuerGenerationAuthorityEvent verifiedProjectionEvent(String canonicalEvent) { + try { + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.verify(canonicalEvent); + if (!event.canonicalJson().equals(canonicalEvent)) { + throw new IllegalArgumentException("projection event is not canonical"); + } + return verifyEvent(event); + } catch (EvidenceRejected rejected) { + throw new IllegalArgumentException("projection event evidence is malformed", rejected); + } + } + + private static void validateEvidenceMapKeys( + Map evidence, BigInteger sequence, String sequenceText) { + for (Map.Entry entry : evidence.entrySet()) { + if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String)) { + throw new IllegalArgumentException("projection applied-source evidence is malformed"); + } + positiveDecimal(key, "projection evidence sequence"); + if (!sequence.equals(ZERO) && !sequenceText.equals(key)) { + throw new IllegalArgumentException("projection evidence is not the current checkpoint"); + } + } + } + + private static String requiredString(Map fields, String name) { + Object value = fields.get(name); + if (!(value instanceof String text)) { + throw new IllegalArgumentException("projection field " + name + " must be a string"); + } + return text; + } + + private static BigInteger positiveDecimal(String value, String label) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return new BigInteger(value); + } + + private static BigInteger nonnegativeDecimal(String value, String label) { + if (value == null || !value.matches("(?:0|[1-9][0-9]*)")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); + } + return new BigInteger(value); + } + + private static void requireAppliedAt(String appliedAt) { + if (appliedAt == null || appliedAt.isBlank()) { + throw reject(QuarantineReason.APPLIED_AT_REQUIRED); + } + } + + private static Optional> immutableObserved(Map observed) { + if (observed == null) { + return Optional.empty(); + } + try { + return Optional.of(immutableMap(observed)); + } catch (IllegalArgumentException malformed) { + return Optional.empty(); + } + } + + private static Map immutableMap(Map source) { + if (source == null) { + throw new IllegalArgumentException("projection maps must not be null"); + } + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw new IllegalArgumentException("projection map keys must be strings"); + } + copy.put(key, immutableValue(entry.getValue())); + } + return Collections.unmodifiableMap(copy); + } + + private static Object immutableValue(Object value) { + if (value instanceof Map map) { + return immutableMap(map); + } + if (value instanceof List list) { + List copy = new ArrayList<>(list.size()); + for (Object item : list) { + copy.add(immutableValue(item)); + } + return Collections.unmodifiableList(copy); + } + if (value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean) { + return value; + } + throw new IllegalArgumentException("projection values must be JSON-compatible"); + } + + private static EvidenceRejected reject(QuarantineReason reason) { + return new EvidenceRejected(reason); + } + + private record Checkpoint( + String issuerId, + String streamKey, + BigInteger generation, + BigInteger sourceVersion, + BigInteger sequence, + IssuerGenerationAuthorityEvent latestEvent) {} + + private record VerifiedReadback( + Checkpoint snapshot, Optional selectedEvent) {} + + private record ExistingProjection( + String issuerId, + BigInteger generation, + BigInteger sourceVersion, + BigInteger sequence, + String streamKey, + IssuerGenerationAuthorityEvent latestEvent) {} + + private static final class EvidenceRejected extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final QuarantineReason reason; + + private EvidenceRejected(QuarantineReason reason) { + this.reason = reason; + } + + private QuarantineReason reason() { + return reason; + } + } + + public sealed interface Decision permits Mutation, NoOp, Quarantine {} + + public enum MutationKind { + BOOTSTRAP, + ADVANCE + } + + public enum NoOpReason { + EXACT_DUPLICATE, + VERIFIED_HISTORICAL_DUPLICATE + } + + public enum QuarantineReason { + APPLIED_AT_REQUIRED, + BOOTSTRAP_REQUIRES_CURRENT_READBACK, + CURRENT_CHECKPOINT_CONFLICT, + CURRENT_CHECKPOINT_REGRESSED, + DUPLICATE_EVENT_CONFLICT, + EVENT_GENERATION_REGRESSED, + EVENT_SEQUENCE_GAP, + EVENT_SOURCE_VERSION_REGRESSED, + HISTORICAL_EVENT_PROGRESS_CONFLICT, + ISSUER_OR_STREAM_CHANGED, + MALFORMED_ACCOUNT_READBACK, + MALFORMED_EXISTING_PROJECTION, + MISSING_EXISTING_PROJECTION, + SELECTED_EVENT_REQUIRED + } + + /** An immutable atomic compare-and-set proposal. Empty expected state means bootstrap. */ + public record Mutation( + Optional> expectedProjection, + Map nextProjection, + MutationKind kind) + implements Decision { + public Mutation { + expectedProjection = Objects.requireNonNull(expectedProjection, "expected state is required"); + expectedProjection = + expectedProjection.map(IssuerAuthorityProjectionTransitions::immutableMap); + nextProjection = + immutableMap(Objects.requireNonNull(nextProjection, "next state is required")); + Objects.requireNonNull(kind, "mutation kind is required"); + } + + public Map nextProjection() { + return immutableMap(nextProjection); + } + } + + public record NoOp(NoOpReason reason) implements Decision { + public NoOp { + Objects.requireNonNull(reason, "no-op reason is required"); + } + } + + /** + * Quarantine contains the exact observed state when it could be represented as immutable JSON. + */ + public record Quarantine( + Optional> expectedProjection, QuarantineReason reason) + implements Decision { + public Quarantine { + expectedProjection = Objects.requireNonNull(expectedProjection, "expected state is required"); + expectedProjection = + expectedProjection.map(IssuerAuthorityProjectionTransitions::immutableMap); + Objects.requireNonNull(reason, "quarantine reason is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java new file mode 100644 index 0000000000..beedbf3b7c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java @@ -0,0 +1,418 @@ +package net.firedevops.firemud.gamesession.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +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.Duration; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Decision; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Mutation; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.NoOp; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Quarantine; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; + +/** Explicitly owned, unwired Coordination Redis store for the derived issuer projection. */ +public final class RedisIssuerAuthorityProjectionStore implements AutoCloseable { + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + private static final TypeReference> OBJECT_MAP = new TypeReference<>() {}; + private static final DefaultRedisScript CAS_SCRIPT = casScript(); + private static final byte[] CAS_SCRIPT_SHA256 = scriptDigest(); + private static final Duration COMMAND_TIMEOUT = Duration.ofSeconds(3); + + private final String expectedWorkloadNamespace; + private final CoordinationEndpoint coordinationEndpoint; + private final CacheRateLimitEndpoint cacheRateLimitEndpoint; + + private LettuceConnectionFactory connectionFactory; + private StringRedisTemplate redisTemplate; + private boolean closed; + + /** + * Captures explicit role endpoints and credentials. This constructor creates no Spring bean and + * opens no connection; callers must invoke {@link #init()} explicitly. + */ + public RedisIssuerAuthorityProjectionStore( + String expectedWorkloadNamespace, + CoordinationEndpoint coordinationEndpoint, + CacheRateLimitEndpoint cacheRateLimitEndpoint) { + if (!GrpcPeerIdentity.isValidNamespace(expectedWorkloadNamespace)) { + throw new IllegalArgumentException("A valid expected workload namespace is required"); + } + this.expectedWorkloadNamespace = expectedWorkloadNamespace; + this.coordinationEndpoint = + Objects.requireNonNull(coordinationEndpoint, "Coordination endpoint is required"); + this.cacheRateLimitEndpoint = + Objects.requireNonNull(cacheRateLimitEndpoint, "Cache/Rate-Limit endpoint is required"); + validateDistinctEndpoints(coordinationEndpoint, cacheRateLimitEndpoint); + } + + /** Initializes this store's private Coordination-only Lettuce client and String template. */ + public synchronized void init() { + if (closed) { + throw new IllegalStateException("issuer projection store is closed"); + } + if (connectionFactory != null) { + return; + } + verifyScriptDigest(); + + RedisStandaloneConfiguration redisConfiguration = + new RedisStandaloneConfiguration(coordinationEndpoint.host(), coordinationEndpoint.port()); + redisConfiguration.setUsername(coordinationEndpoint.principal()); + redisConfiguration.setPassword(RedisPassword.of(coordinationEndpoint.password())); + LettuceClientConfiguration clientConfiguration = + LettuceClientConfiguration.builder().commandTimeout(COMMAND_TIMEOUT).build(); + + LettuceConnectionFactory newConnectionFactory = + new LettuceConnectionFactory(redisConfiguration, clientConfiguration); + newConnectionFactory.afterPropertiesSet(); + StringRedisTemplate newTemplate = new StringRedisTemplate(newConnectionFactory); + newTemplate.afterPropertiesSet(); + connectionFactory = newConnectionFactory; + redisTemplate = newTemplate; + } + + /** + * Applies one privately verified Account readback. This path performs one exact GET and at most + * one registered owner-script call; it never retries after a stale result. + */ + public synchronized ApplyResult apply(SourceReadback readback, String appliedAt) { + requireInitialized(); + if (readback == null) { + return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); + } + if (!expectedWorkloadNamespace.equals(readback.targetNamespace())) { + return quarantined("ACCOUNT_NAMESPACE_MISMATCH", Optional.empty()); + } + if (readback.sourceSnapshot() == null || readback.sourceSnapshot().issuerId() == null) { + return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); + } + + final String key; + try { + key = + IssuerAuthorityProjectionRedisContract.keyForIssuer(readback.sourceSnapshot().issuerId()); + } catch (IllegalArgumentException malformed) { + return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); + } + + StoredValue observed = readStoredValue(key); + if (observed.bytes() != null && observed.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + + final String observedJson; + final Decision decision; + if (observed.bytes() == null) { + observedJson = null; + decision = IssuerAuthorityProjectionTransitions.bootstrap(readback, appliedAt); + } else { + try { + observedJson = decodeUtf8(observed.bytes()); + Map observedProjection = parseProjection(observedJson); + decision = + IssuerAuthorityProjectionTransitions.decide(observedProjection, readback, appliedAt); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_STORED_JSON", Optional.empty()); + } + } + + if (decision instanceof Quarantine quarantine) { + return quarantined(quarantine.reason().name(), Optional.of(decision)); + } + if (decision instanceof NoOp) { + if (observedJson == null) { + return quarantined("NO_OP_WITHOUT_EXISTING_PROJECTION", Optional.of(decision)); + } + String result = executeRegistered(key, "VERIFY", observedJson, ""); + if ("REPLAY".equals(result)) { + return new ApplyResult( + Outcome.NO_OP, + Optional.of(new ProjectionSnapshot(key, observedJson)), + Optional.empty(), + Optional.of(decision)); + } + return mutationOutcome(result, key, observedJson, decision); + } + if (!(decision instanceof Mutation mutation)) { + return quarantined("UNSUPPORTED_TRANSITION_DECISION", Optional.of(decision)); + } + + String expectedMode = observedJson == null ? "ABSENT" : "PRESENT"; + if (mutation.expectedProjection().isPresent() != (observedJson != null)) { + return quarantined("TRANSITION_EXPECTATION_MISMATCH", Optional.of(decision)); + } + String candidateJson; + try { + candidateJson = serializeProjection(mutation.nextProjection()); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_CANDIDATE", Optional.of(decision)); + } + String result = + executeRegistered( + key, expectedMode, observedJson == null ? "" : observedJson, candidateJson); + return mutationOutcome(result, key, candidateJson, decision); + } + + @Override + public synchronized void close() { + closed = true; + if (connectionFactory != null) { + connectionFactory.destroy(); + connectionFactory = null; + redisTemplate = null; + } + } + + private ApplyResult mutationOutcome( + String result, String key, String candidateJson, Decision decision) { + if ("APPLIED".equals(result)) { + return new ApplyResult( + Outcome.APPLIED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.empty(), + Optional.of(decision)); + } + if ("REPLAY".equals(result)) { + return new ApplyResult( + Outcome.REPLAYED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.empty(), + Optional.of(decision)); + } + if ("STALE".equals(result)) { + return new ApplyResult( + Outcome.STALE, Optional.empty(), Optional.empty(), Optional.of(decision)); + } + if ("TTL_PRESENT".equals(result)) { + return quarantined("TTL_PRESENT", Optional.of(decision)); + } + if ("INVALID".equals(result)) { + return quarantined("REGISTERED_SCRIPT_REJECTED_INVOCATION", Optional.of(decision)); + } + return quarantined( + "UNKNOWN_REGISTERED_SCRIPT_RESULT:" + Objects.toString(result, "null"), + Optional.of(decision)); + } + + private String executeRegistered( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + RedisInvocationContract invocation = + IssuerAuthorityProjectionRedisContract.prepareInvocation( + key, expectedMode, expectedBytes, candidateBytes); + RedisScriptDescriptor descriptor = invocation.descriptor(); + if (descriptor != IssuerAuthorityProjectionRedisContract.descriptor() + || !descriptor.scriptId().equals(IssuerAuthorityProjectionRedisContract.SCRIPT_ID) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !IssuerAuthorityProjectionRedisContract.PRINCIPAL.equals(descriptor.principal())) { + throw new IllegalStateException( + "issuer projection invocation is not its registered owner contract"); + } + return redisTemplate.execute( + CAS_SCRIPT, List.of(key), expectedMode, expectedBytes, candidateBytes); + } + + private StoredValue readStoredValue(String key) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + return redisTemplate.execute( + (RedisCallback) + connection -> { + byte[] value = connection.stringCommands().get(keyBytes); + long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new StoredValue(value, ttlMillis); + }); + } + + private static Map parseProjection(String json) throws IOException { + JsonNode root = JSON.readTree(json); + if (root == null || !root.isObject()) { + throw new IllegalArgumentException("stored issuer projection must be a JSON object"); + } + return JSON.convertValue(root, OBJECT_MAP); + } + + private static String serializeProjection(Map projection) throws IOException { + return JSON.writeValueAsString(projection); + } + + private static String decodeUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private void requireInitialized() { + if (closed || redisTemplate == null) { + throw new IllegalStateException("issuer projection store requires explicit init()"); + } + } + + private static void validateDistinctEndpoints( + CoordinationEndpoint coordination, CacheRateLimitEndpoint cache) { + if (normalizeHost(coordination.host()).equals(normalizeHost(cache.host())) + && coordination.port() == cache.port()) { + throw new IllegalArgumentException( + "Coordination and Cache/Rate-Limit Redis endpoints must be distinct"); + } + } + + private static String normalizeHost(String host) { + String normalized = host.toLowerCase(Locale.ROOT); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + normalized = normalized.substring(1, normalized.length() - 1); + } + while (normalized.endsWith(".")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + return normalized; + } + + private static DefaultRedisScript casScript() { + DefaultRedisScript script = new DefaultRedisScript<>(); + script.setLocation(new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH)); + script.setResultType(String.class); + return script; + } + + private static byte[] scriptDigest() { + try (var input = + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH) + .getInputStream()) { + byte[] bytes = input.readAllBytes(); + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (IOException exception) { + throw new ExceptionInInitializerError(exception); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static void verifyScriptDigest() { + String actual = java.util.HexFormat.of().formatHex(CAS_SCRIPT_SHA256); + if (!IssuerAuthorityProjectionRedisContract.descriptor().sha256().equals(actual)) { + throw new IllegalStateException( + "issuer projection Lua resource digest differs from its registration"); + } + } + + private static ApplyResult quarantined(String detail, Optional decision) { + return new ApplyResult(Outcome.QUARANTINED, Optional.empty(), Optional.of(detail), decision); + } + + private record StoredValue(byte[] bytes, long ttlMillis) {} + + public enum Outcome { + APPLIED, + NO_OP, + QUARANTINED, + REPLAYED, + STALE + } + + /** + * Immutable JSON snapshot returned for observation; it grants no admission or rebind authority. + */ + public record ProjectionSnapshot(String key, String json) { + public ProjectionSnapshot { + Objects.requireNonNull(key, "projection key is required"); + Objects.requireNonNull(json, "projection JSON is required"); + } + } + + public record ApplyResult( + Outcome outcome, + Optional snapshot, + Optional detail, + Optional transitionDecision) { + public ApplyResult { + Objects.requireNonNull(outcome, "outcome is required"); + snapshot = Objects.requireNonNull(snapshot, "snapshot optional is required"); + detail = Objects.requireNonNull(detail, "detail optional is required"); + transitionDecision = + Objects.requireNonNull(transitionDecision, "transition decision optional is required"); + } + } + + /** Explicit Coordination endpoint and ACL identity; the principal is not caller-selectable. */ + public record CoordinationEndpoint(String host, int port, String principal, String password) { + public CoordinationEndpoint { + validateHost(host, "Coordination host"); + validatePort(port, "Coordination port"); + if (!IssuerAuthorityProjectionRedisContract.PRINCIPAL.equals(principal)) { + throw new IllegalArgumentException("Coordination principal must be gamesession_coord_app"); + } + if (password == null || password.isBlank()) { + throw new IllegalArgumentException("Coordination ACL credential is required"); + } + } + + @Override + public String toString() { + return "CoordinationEndpoint[host=" + + host + + ", port=" + + port + + ", principal=" + + principal + + ", password=]"; + } + } + + /** Required separate Cache/Rate-Limit endpoint used only for collision validation. */ + public record CacheRateLimitEndpoint(String host, int port) { + public CacheRateLimitEndpoint { + validateHost(host, "Cache/Rate-Limit host"); + validatePort(port, "Cache/Rate-Limit port"); + } + } + + private static void validateHost(String host, String label) { + if (host == null + || host.isBlank() + || !host.equals(host.trim()) + || host.contains("://") + || host.chars().anyMatch(Character::isWhitespace) + || host.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " must be an explicit host or IP address"); + } + } + + private static void validatePort(int port, String label) { + if (port < 1 || port > 65535) { + throw new IllegalArgumentException(label + " must be between 1 and 65535"); + } + } +} diff --git a/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua b/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua new file mode 100644 index 0000000000..a7b32ccc60 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua @@ -0,0 +1,54 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return 'INVALID' +end + +local mode = ARGV[1] +local expectedBytes = ARGV[2] +local candidateBytes = ARGV[3] + +if mode ~= 'ABSENT' and mode ~= 'PRESENT' and mode ~= 'VERIFY' then + return 'INVALID' +end + +if mode == 'VERIFY' then + if expectedBytes == '' or candidateBytes ~= '' then + return 'INVALID' + end +elseif mode == 'ABSENT' then + if expectedBytes ~= '' or candidateBytes == '' then + return 'INVALID' + end +elseif expectedBytes == '' or candidateBytes == '' then + return 'INVALID' +end + +local currentBytes = redis.call('GET', KEYS[1]) +if currentBytes ~= false and redis.call('PTTL', KEYS[1]) ~= -1 then + return 'TTL_PRESENT' +end + +if mode == 'VERIFY' then + if currentBytes == expectedBytes then + return 'REPLAY' + end + return 'STALE' +end + +if currentBytes == candidateBytes then + return 'REPLAY' +end + +if mode == 'ABSENT' then + if currentBytes ~= false then + return 'STALE' + end + redis.call('SET', KEYS[1], candidateBytes) + return 'APPLIED' +end + +if currentBytes ~= expectedBytes then + return 'STALE' +end + +redis.call('SET', KEYS[1], candidateBytes) +return 'APPLIED' diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java index f9d61b69f8..0a5dc3fc86 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java @@ -2,6 +2,7 @@ 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.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -12,19 +13,27 @@ 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.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; @@ -115,23 +124,44 @@ void trustedButWrongGameSessionPeerIsDeniedBeforeProducerAccess(String clientIde void missingClientCertificateFailsTheRequiredTlsHandshakeBeforeProducerAccess() throws Exception { AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); Server server = startServer("account", producer); - var channel = - NettyChannelBuilder.forAddress("localhost", server.getPort()) - .sslContext( - GrpcSslContexts.forClient().trustManager(certificate("ca.crt").toFile()).build()) - .build(); + SSLContext trustOnlyClientContext = trustOnlyClientContext(); try { - assertThatThrownBy( - () -> - IssuerAuthorityServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .readIssuerAuthorityForRuntime(validRequest())) - .satisfies( - failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + Throwable handshakeFailure = + catchThrowable( + () -> { + try (Socket transport = new Socket()) { + transport.connect(new InetSocketAddress("127.0.0.1", server.getPort()), 5_000); + try (SSLSocket socket = + (SSLSocket) + trustOnlyClientContext + .getSocketFactory() + .createSocket(transport, "127.0.0.1", server.getPort(), true)) { + socket.setSoTimeout(5_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setApplicationProtocols(new String[] {"h2"}); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + socket.setSSLParameters(parameters); + socket.startHandshake(); + // TLS 1.3 can deliver the server's certificate rejection after the client's + // handshake returns. Observe that alert rather than accepting a silent close. + socket + .getOutputStream() + .write( + "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + socket.getInputStream().read(); + } + } + }); + + assertThat(handshakeFailure) + .as("the REQUIRED client-certificate TLS handshake must fail") + .isNotNull(); + assertThat(TlsTestSupport.isTlsHandshakeRejection(handshakeFailure)) + .as("failure must identify client-certificate rejection: %s", describe(handshakeFailure)) + .isTrue(); verifyNoInteractions(producer); } finally { - channel.shutdownNow(); - channel.awaitTermination(2, TimeUnit.SECONDS); stop(server); } } @@ -222,6 +252,39 @@ private Path certificate(String name) throws IOException { } } + private SSLContext trustOnlyClientContext() throws Exception { + X509Certificate caCertificate; + try (InputStream input = Files.newInputStream(certificate("ca.crt"))) { + caCertificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null); + trustStore.setCertificateEntry("test-ca", caCertificate); + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(new KeyManager[0], trustManagers.getTrustManagers(), null); + return context; + } + + private static String describe(Throwable failure) { + StringBuilder description = new StringBuilder(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (description.length() > 0) { + description.append(" <- "); + } + description.append(cause.getClass().getSimpleName()); + if (cause.getMessage() != null) { + description.append(": ").append(cause.getMessage()); + } + } + return description.toString(); + } + private static IssuerGenerationAuthorityEvent event( String requestId, long sequence, long generation, long sourceVersion) { return IssuerGenerationAuthorityEventV1Codec.seal( @@ -248,14 +311,6 @@ private static IssuerGenerationAuthorityEvent event( Long.toString(sourceVersion))); } - private static net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest - validRequest() { - return net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest.newBuilder() - .setIssuerId(ISSUER_ID) - .setRequestId(CURRENT_READ_REQUEST_ID) - .build(); - } - private static void stop(Server server) throws InterruptedException { server.shutdownNow(); server.awaitTermination(2, TimeUnit.SECONDS); diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java new file mode 100644 index 0000000000..9d0c8700b9 --- /dev/null +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java @@ -0,0 +1,275 @@ +package crossservice.net.firedevops.firemud.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityGrpcService; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL-backed Account issuer readback composed with the physical Game Session mTLS client. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest { + private static final String NAMESPACE = "test"; + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + private static final String BOOTSTRAP_READ_REQUEST_ID = "11111111-1111-4111-8111-111111111111"; + private static final String CURRENT_READ_REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String HISTORICAL_READ_REQUEST_ID = "33333333-3333-4333-8333-333333333333"; + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir private Path tempDir; + + private final Map copiedCertificates = new HashMap<>(); + + @Test + void postgresIssuerSourceReturnsBootstrapCurrentAndHistoricalEvidenceOverSocketMtls() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + Server server = startServer(producer); + + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + AccountIssuerAuthorityClient.SourceReadback bootstrap = + client.readCurrent(BOOTSTRAP_READ_REQUEST_ID); + assertThat(bootstrap.requestId()).isEqualTo(BOOTSTRAP_READ_REQUEST_ID); + assertThat(bootstrap.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(bootstrap.sourceSnapshot().issuerId()).isEqualTo(ISSUER_ID); + assertThat(bootstrap.sourceSnapshot().sourceScope()).isEqualTo("issuer/" + ISSUER_ID); + assertThat(bootstrap.sourceSnapshot().outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(bootstrap.sourceSnapshot().issuerAuthGeneration()).isEqualTo("1"); + assertThat(bootstrap.sourceSnapshot().sourceVersion()).isEqualTo("1"); + assertThat(bootstrap.sourceSnapshot().outboxSequence()).isEqualTo("0"); + assertThat(bootstrap.sourceSnapshot().latestEvent()).isEmpty(); + assertThat(bootstrap.requestedEvent()).isEmpty(); + + IssuerGenerationAuthorityEvent first = producer.advance(ISSUER_ID, UUID.randomUUID(), 1L, 1L); + IssuerGenerationAuthorityEvent second = + producer.advance(ISSUER_ID, UUID.randomUUID(), 2L, 2L); + + AccountIssuerAuthorityClient.SourceReadback current = + client.readCurrent(CURRENT_READ_REQUEST_ID); + AccountIssuerAuthorityClient.SourceReadback historical = + client.readCommittedEvent(HISTORICAL_READ_REQUEST_ID, "1"); + + assertThat(current.requestId()).isEqualTo(CURRENT_READ_REQUEST_ID); + assertThat(current.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(current.sourceSnapshot().issuerId()).isEqualTo(ISSUER_ID); + assertThat(current.sourceSnapshot().sourceScope()).isEqualTo("issuer/" + ISSUER_ID); + assertThat(current.sourceSnapshot().outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(current.sourceSnapshot().issuerAuthGeneration()).isEqualTo("3"); + assertThat(current.sourceSnapshot().sourceVersion()).isEqualTo("3"); + assertThat(current.sourceSnapshot().outboxSequence()).isEqualTo("2"); + assertThat(current.sourceSnapshot().latestEvent()).isPresent(); + assertSameEvent(second, current.sourceSnapshot().latestEvent().orElseThrow()); + assertThat(current.requestedEvent()).isEmpty(); + + assertThat(historical.requestId()).isEqualTo(HISTORICAL_READ_REQUEST_ID); + assertThat(historical.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(historical.sourceSnapshot().issuerId()).isEqualTo(ISSUER_ID); + assertThat(historical.sourceSnapshot().sourceScope()).isEqualTo("issuer/" + ISSUER_ID); + assertThat(historical.sourceSnapshot().outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(historical.sourceSnapshot().issuerAuthGeneration()).isEqualTo("3"); + assertThat(historical.sourceSnapshot().sourceVersion()).isEqualTo("3"); + assertThat(historical.sourceSnapshot().outboxSequence()).isEqualTo("2"); + assertThat(historical.sourceSnapshot().latestEvent()).isPresent(); + assertSameEvent(second, historical.sourceSnapshot().latestEvent().orElseThrow()); + assertThat(historical.requestedEvent()).isPresent(); + assertSameEvent(first, historical.requestedEvent().orElseThrow()); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void trustedButWrongGameSessionIdentityIsDeniedWithoutChangingPostgresSource( + String clientIdentity) throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + Server server = startServer(producer); + + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), clientIdentity)) { + client.init(); + IssuerAuthoritySnapshot before = producer.readCurrent(ISSUER_ID); + + assertThatThrownBy(() -> client.readCurrent(CURRENT_READ_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(producer.readCurrent(ISSUER_ID)).isEqualTo(before); + } finally { + stop(server); + } + } + + private AccountFixture newAccountFixture() { + String schema = "issuer_authority_grpc_proof_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + accountMigrationDirectory()) + .load() + .migrate(); + + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + return new AccountFixture(generations, outbox, transactionDsl, transactionManager); + } + + private static Path accountMigrationDirectory() { + Path current = Path.of("").toAbsolutePath().normalize(); + while (current != null) { + Path accountMigrations = + current.resolve("services/account-service/src/main/resources/db/migration"); + if (Files.isRegularFile(current.resolve("settings.gradle.kts")) + && Files.isDirectory(accountMigrations)) { + return accountMigrations; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate the Account service migration directory"); + } + + private Server startServer(AccountIssuerAuthorityEventProducer producer) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + certificate("account.crt").toFile(), certificate("account.key").toFile()) + .trustManager(certificate("ca.crt").toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountIssuerAuthorityGrpcService(producer, NAMESPACE), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AccountIssuerAuthorityClient newClient(int port, String clientIdentity) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate(clientIdentity + ".crt").toString()); + tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); + tls.setCaCert(certificate("ca.crt").toString()); + return new AccountIssuerAuthorityClient( + endpoints, + tls, + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + ISSUER_ID); + } + + private Path certificate(String name) throws IOException { + Path existing = copiedCertificates.get(name); + if (existing != null) { + return existing; + } + + String resourcePath = "/certs/issuer-authority/" + name; + try (InputStream resource = + AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.class.getResourceAsStream( + resourcePath)) { + if (resource == null) { + throw new IllegalStateException("Missing issuer-authority TLS fixture: " + resourcePath); + } + Path copied = tempDir.resolve(name); + Files.copy(resource, copied); + copiedCertificates.put(name, copied); + return copied; + } + } + + private void assertSameEvent( + IssuerGenerationAuthorityEvent expected, IssuerGenerationAuthorityEvent actual) { + assertThat(actual.canonicalJson()).isEqualTo(expected.canonicalJson()); + assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + server.awaitTermination(2, TimeUnit.SECONDS); + } + + private record AccountFixture( + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager) { + private void seedIssuer() { + new TransactionTemplate(transactionManager) + .execute(status -> generations.initializeIssuerIfAbsent(ISSUER_ID)); + } + + private AccountIssuerAuthorityEventProducer producer() { + return new AccountIssuerAuthorityEventProducer( + ISSUER_ID, generations, outbox, transactionDsl, transactionManager); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java new file mode 100644 index 0000000000..187109e6be --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java @@ -0,0 +1,360 @@ +package integration.net.firedevops.firemud.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ApplyResult; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.Outcome; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.RedisScript; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Redis integration; Account readbacks are minted by the client over its mocked response seam. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class IssuerAuthorityProjectionRedisIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String QUERY_ID = "11111111-1111-4111-8111-111111111111"; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + private static final String COORD_PASSWORD = "issuer-projection-integration-secret"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final RedisScript CAS_SCRIPT = + RedisScript.of( + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH), + String.class); + + @Container + static final GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--user", + "gamesession_coord_app", + "on", + ">" + COORD_PASSWORD, + "~session:game:auth:issuer-generation:v1:*", + "+get", + "+set", + "+pttl", + "+eval", + "+evalsha", + "+script|exists", + "+script|load"); + + private String issuerId; + private RedisIssuerAuthorityProjectionStore store; + private LettuceConnectionFactory adminConnectionFactory; + private StringRedisTemplate adminTemplate; + + @BeforeEach + void startOwnerStoreAndTestOnlyAdminReadback() { + issuerId = "https://accounts.example.test/issuer/" + UUID.randomUUID(); + store = + new RedisIssuerAuthorityProjectionStore( + NAMESPACE, + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + redis.getHost(), + redis.getMappedPort(6379), + "gamesession_coord_app", + COORD_PASSWORD), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( + "redis-cache.test.invalid", 6380)); + store.init(); + + adminConnectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379))); + adminConnectionFactory.afterPropertiesSet(); + adminTemplate = new StringRedisTemplate(adminConnectionFactory); + adminTemplate.afterPropertiesSet(); + } + + @AfterEach + void closeConnections() { + if (store != null) { + store.close(); + } + if (adminConnectionFactory != null) { + adminConnectionFactory.destroy(); + } + } + + @Test + void authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSnapshots() + throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 1); + SourceReadback current = readback("2", "3", "1", first, null); + + ApplyResult bootstrap = store.apply(current, "2026-10-02T11:00:00Z"); + assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot firstSnapshot = bootstrap.snapshot().orElseThrow(); + assertThat(firstSnapshot.key()).isEqualTo(key()); + assertThat(parse(firstSnapshot.json()).path("lastAppliedSourceOutboxSequence").asText()) + .isEqualTo("1"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(firstSnapshot.json()); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + + IssuerGenerationAuthorityEvent second = event("2", "3", "4", 2); + SourceReadback selected = readback("3", "4", "2", second, second); + ApplyResult advanced = store.apply(selected, "2026-10-02T11:01:00Z"); + assertThat(advanced.outcome()).isEqualTo(Outcome.APPLIED); + String deterministicCandidate = advanced.snapshot().orElseThrow().json(); + assertThat(parse(deterministicCandidate).path("lastAppliedSourceOutboxSequence").asText()) + .isEqualTo("2"); + + ApplyResult exactDuplicate = store.apply(selected, "ignored-for-no-op"); + assertThat(exactDuplicate.outcome()).isEqualTo(Outcome.NO_OP); + assertThat(exactDuplicate.snapshot().orElseThrow().json()).isEqualTo(deterministicCandidate); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(deterministicCandidate); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEvidence() + throws Exception { + ApplyResult bootstrap = + store.apply(readback("1", "1", "0", null, null), "2026-10-02T10:59:00Z"); + + assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); + JsonNode projection = parse(bootstrap.snapshot().orElseThrow().json()); + assertThat(projection.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("0"); + assertThat(projection.has("sourceEventId")).isFalse(); + assertThat(projection.has("sourceEventDigest")).isFalse(); + assertThat(projection.path("appliedSourceEvidence").isEmpty()).isTrue(); + assertThat(adminTemplate.opsForValue().get(key())) + .isEqualTo(bootstrap.snapshot().orElseThrow().json()); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void gapAndAuthenticatedOlderDuplicateHaveDistinctNoMutationOutcomes() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 3); + IssuerGenerationAuthorityEvent second = event("2", "3", "4", 4); + assertThat(store.apply(readback("2", "3", "1", first, null), "stable-1").outcome()) + .isEqualTo(Outcome.APPLIED); + assertThat(store.apply(readback("3", "4", "2", second, second), "stable-2").outcome()) + .isEqualTo(Outcome.APPLIED); + String before = adminTemplate.opsForValue().get(key()); + + IssuerGenerationAuthorityEvent fourth = event("4", "6", "7", 6); + ApplyResult gap = store.apply(readback("6", "7", "4", fourth, fourth), "ignored-for-gap"); + assertThat(gap.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(gap.detail()).contains("EVENT_SEQUENCE_GAP"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); + + ApplyResult olderDuplicate = + store.apply(readback("3", "4", "2", second, first), "ignored-for-older-duplicate"); + assertThat(olderDuplicate.outcome()).isEqualTo(Outcome.NO_OP); + assertThat(olderDuplicate.transitionDecision().orElseThrow()) + .isInstanceOf(IssuerAuthorityProjectionTransitions.NoOp.class); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void staleExpectedBytesAreNonMutatingThroughTheRegisteredOwnerScript() { + String key = key(); + adminTemplate.opsForValue().set(key, "newer exact bytes"); + String result = executeRegistered(key, "PRESENT", "older exact bytes", "stale candidate bytes"); + + assertThat(result).isEqualTo("STALE"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo("newer exact bytes"); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl() throws Exception { + String key = key(); + String unknownFieldJson = "{\"schemaVersion\":\"unknown\",\"extra\":true}"; + adminTemplate.opsForValue().set(key, unknownFieldJson); + IssuerGenerationAuthorityEvent event = event("2", "3", "4", 7); + + ApplyResult unknown = store.apply(readback("3", "4", "2", event, event), "stable-time"); + + assertThat(unknown.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(unknownFieldJson); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + + String duplicatePropertyJson = + "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"," + + "\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"}"; + adminTemplate.opsForValue().set(key, duplicatePropertyJson); + ApplyResult duplicateProperty = + store.apply(readback("3", "4", "2", event, event), "stable-time"); + assertThat(duplicateProperty.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(duplicatePropertyJson); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 8); + assertThat(store.apply(readback("2", "3", "1", first, null), "stable-time").outcome()) + .isEqualTo(Outcome.APPLIED); + String before = adminTemplate.opsForValue().get(key()); + adminTemplate.expire(key(), 30, TimeUnit.SECONDS); + Long beforeTtl = adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS); + + IssuerGenerationAuthorityEvent second = event("2", "3", "4", 9); + ApplyResult result = store.apply(readback("3", "4", "2", second, second), "stable-time"); + + assertThat(result.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(result.detail()).contains("TTL_PRESENT"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(beforeTtl); + } + + private SourceReadback readback( + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest, + IssuerGenerationAuthorityEvent selected) + throws Exception { + String scope = "issuer/" + issuerId; + String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope; + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(scope) + .setOutboxStreamKey(streamKey) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latest != null) { + snapshot.setLatestEventCanonicalJson(latest.canonicalJson()); + } + ReadIssuerAuthorityForRuntimeResponse.Builder response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(NAMESPACE) + .setRequestId(QUERY_ID) + .setSourceSnapshot(snapshot.build()); + if (selected != null) { + response.setRequestedEventCanonicalJson(selected.canonicalJson()); + } + + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response.build()); + AccountIssuerAuthorityClient client = newClient(stub); + if (selected == null) { + return client.readCurrent(QUERY_ID); + } + return client.readCommittedEvent(QUERY_ID, selected.outboxSequence()); + } + + private String executeRegistered( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); + var request = + new InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of(key), + List.of(expectedMode, expectedBytes, candidateBytes)); + var invocation = IssuerAuthorityProjectionRedisContract.registry().prepareInvocation(request); + assertThat(invocation.descriptor()).isSameAs(descriptor); + return adminTemplate.execute( + CAS_SCRIPT, List.of(key), expectedMode, expectedBytes, candidateBytes); + } + + private String key() { + return IssuerAuthorityProjectionRedisContract.keyForIssuer(issuerId); + } + + private static JsonNode parse(String json) throws Exception { + return JSON.readTree(json); + } + + private IssuerGenerationAuthorityEvent event( + String sequence, String generation, String sourceVersion, int identity) { + String requestId = String.format(Locale.ROOT, "00000000-0000-4000-8000-%012d", identity); + String scope = "issuer/" + issuerId; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", EVENT_ID_PREFIX + requestId, + "requestId", requestId, + "issuerId", issuerId, + "sourceScope", scope, + "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, + "outboxSequence", sequence, + "issuerAuthGeneration", generation, + "sourceVersion", sourceVersion)); + } + + private AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub) throws Exception { + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + issuerId); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + return tls; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java new file mode 100644 index 0000000000..2718de39e4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java @@ -0,0 +1,107 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; +import org.junit.jupiter.api.Test; + +class IssuerAuthorityProjectionRedisContractTest { + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + + @Test + void descriptorPinsOwnerPrincipalRoleResourceKeyAndArguments() { + var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); + + assertThat(descriptor.scriptId()).isEqualTo("game-session.issuer-authority-projection.v1"); + assertThat(descriptor.resourcePath()).isEqualTo("redis/issuer_authority_projection_cas.lua"); + assertThat(descriptor.owner()).isEqualTo("game-session-service"); + assertThat(descriptor.principal()).isEqualTo("gamesession_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisRole.COORDINATION); + assertThat(descriptor.resetSensitivity()).isEqualTo(ResetSensitivity.CLUSTER); + assertThat(descriptor.lossClass()).isEqualTo(LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP); + assertThat(descriptor.tailLossBehavior()) + .contains("quarantine this issuer scope") + .contains("never admit"); + assertThat(IssuerAuthorityProjectionRedisContract.PROJECTION_SCHEMA_VERSION) + .isEqualTo("game-session-auth-issuer-projection/v1"); + assertThat(descriptor.keys()) + .singleElement() + .satisfies( + key -> { + assertThat(key.ownedPrefix()).isEqualTo("session:game:auth:issuer-generation:v1:"); + assertThat(key.hashTagDeclaration()).isEqualTo(HashTagDeclaration.NOT_REQUIRED); + }); + assertThat(descriptor.arguments()) + .extracting(argument -> argument.name()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + assertThat(descriptor.outcomes()) + .extracting(outcome -> outcome.code()) + .containsExactly("APPLIED", "REPLAY", "STALE", "INVALID", "TTL_PRESENT"); + assertThat(IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID)) + .isEqualTo("session:game:auth:issuer-generation:v1:" + ISSUER_ID); + } + + @Test + void registryAcceptsOnlyTheRegisteredOwnerInvocation() { + var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); + String key = IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID); + InvocationRequest valid = + new InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of(key), + List.of("ABSENT", "", "{}")); + + assertThat(IssuerAuthorityProjectionRedisContract.registry().prepareInvocation(valid).keys()) + .containsExactly(key); + assertThatThrownBy( + () -> + IssuerAuthorityProjectionRedisContract.registry() + .prepareInvocation( + new InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + RedisRole.CACHE_RATE_LIMIT, + valid.keys(), + valid.arguments()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Redis role"); + assertThatThrownBy( + () -> + IssuerAuthorityProjectionRedisContract.registry() + .prepareInvocation( + new InvocationRequest( + valid.scriptId(), + "redis/unregistered.lua", + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("script resource path"); + } + + @Test + void ownerKeyBuilderRejectsMissingOrControlCharacterIssuer() { + assertThatThrownBy(() -> IssuerAuthorityProjectionRedisContract.keyForIssuer(" ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> IssuerAuthorityProjectionRedisContract.keyForIssuer("issuer\nother")) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java new file mode 100644 index 0000000000..fef3948c4a --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java @@ -0,0 +1,399 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; +import org.junit.jupiter.api.Test; + +/** Decision/unit proof using AccountIssuerAuthorityClient's existing mocked response seam. */ +class IssuerAuthorityProjectionTransitionsTest { + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String NAMESPACE = "test"; + private static final String QUERY_ID = "11111111-1111-4111-8111-111111111111"; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + + @Test + void bootstrapAtProvedSequenceZeroOmitsEventIdentityAndKeepsCallerAppliedAt() throws Exception { + SourceReadback readback = readback(ISSUER_ID, "1", "1", "0", null, null); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "2026-10-02T11:00:00Z"); + + assertThat(mutation.kind()) + .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.BOOTSTRAP); + assertThat(mutation.expectedProjection()).isEmpty(); + assertThat(mutation.nextProjection()) + .containsEntry("schemaVersion", IssuerAuthorityProjectionTransitions.SCHEMA_VERSION) + .containsEntry("issuerId", ISSUER_ID) + .containsEntry("issuerAuthGeneration", "1") + .containsEntry("lastAppliedSourceOutboxSequence", "0") + .containsEntry("appliedAt", "2026-10-02T11:00:00Z") + .containsEntry("appliedSourceEvidence", Map.of()); + assertThat(mutation.nextProjection()).doesNotContainKeys("sourceEventId", "sourceEventDigest"); + } + + @Test + void bootstrapPositiveCurrentCheckpointRetainsCompleteLatestEventEvidence() throws Exception { + IssuerGenerationAuthorityEvent event = event("7", "92", "105", 1, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "92", "105", "7", event, null); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); + + assertThat(mutation.nextProjection()) + .containsEntry("issuerAuthGeneration", "92") + .containsEntry("lastAppliedSourceOutboxSequence", "7") + .containsEntry("sourceEventId", event.eventId()) + .containsEntry("sourceEventDigest", event.eventDigest()) + .containsEntry("appliedSourceEvidence", Map.of("7", event.canonicalJson())); + assertThat(mutation.nextProjection()).doesNotContainKey("admitted"); + } + + @Test + void mutationCandidateAccessorReturnsDefensiveImmutableCopies() throws Exception { + IssuerGenerationAuthorityEvent event = event("1", "2", "3", 24, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "2", "3", "1", event, null); + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); + + Map first = mutation.nextProjection(); + Map second = mutation.nextProjection(); + + assertThat(first).isEqualTo(second).isNotSameAs(second); + assertThatThrownBy(() -> first.put("unexpected", true)) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void bootstrapRejectsHistoricalSelectionWithoutProducingProjection() throws Exception { + IssuerGenerationAuthorityEvent latest = event("3", "4", "6", 2, ISSUER_ID); + IssuerGenerationAuthorityEvent selected = event("2", "3", "5", 1, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "4", "6", "3", latest, selected); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason + .BOOTSTRAP_REQUIRES_CURRENT_READBACK); + assertThat(decision.expectedProjection()).isEmpty(); + } + + @Test + void selectedContiguousEventAdvancesWatermarkAndCheckpointEvenWhenGenerationIsEqual() + throws Exception { + IssuerGenerationAuthorityEvent prior = event("4", "80", "102", 4, ISSUER_ID); + Map existing = bootstrapProjection("80", "102", "4", prior); + IssuerGenerationAuthorityEvent next = event("5", "80", "103", 5, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "80", "103", "5", next, next); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(mutation.kind()) + .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.ADVANCE); + assertThat(mutation.expectedProjection()).contains(existing); + assertThat(mutation.nextProjection()) + .containsEntry("issuerAuthGeneration", "80") + .containsEntry("lastAppliedSourceOutboxSequence", "5") + .containsEntry("sourceEventId", next.eventId()) + .containsEntry("sourceEventDigest", next.eventDigest()) + .containsEntry("appliedSourceEvidence", Map.of("5", next.canonicalJson())); + } + + @Test + void selectedContiguousEventUsesHigherGenerationWhenAccountAdvancedIt() throws Exception { + IssuerGenerationAuthorityEvent prior = event("4", "80", "102", 20, ISSUER_ID); + Map existing = bootstrapProjection("80", "102", "4", prior); + IssuerGenerationAuthorityEvent next = event("5", "81", "103", 21, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "81", "103", "5", next, next); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(mutation.nextProjection()) + .containsEntry("issuerAuthGeneration", "81") + .containsEntry("lastAppliedSourceOutboxSequence", "5"); + } + + @Test + void sequenceGapQuarantinesWithoutReturningAMutationCandidate() throws Exception { + IssuerGenerationAuthorityEvent prior = event("1", "2", "3", 6, ISSUER_ID); + Map existing = bootstrapProjection("2", "3", "1", prior); + IssuerGenerationAuthorityEvent gap = event("3", "4", "5", 7, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "4", "5", "3", gap, gap); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.EVENT_SEQUENCE_GAP); + assertThat(decision.expectedProjection()).contains(existing); + } + + @Test + void malformedExistingProjectionQuarantinesBeforeConsideringAccountEvent() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "2", 22, ISSUER_ID); + Map validProjection = bootstrapProjection("2", "2", "1", first); + Map malformedProjection = new LinkedHashMap<>(validProjection); + malformedProjection.put("issuerAuthGeneration", "02"); + IssuerGenerationAuthorityEvent next = event("2", "2", "3", 23, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "2", "3", "2", next, next); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide( + malformedProjection, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason.MALFORMED_EXISTING_PROJECTION); + assertThat(decision.expectedProjection()).contains(malformedProjection); + } + + @Test + void exactDuplicateIsNoOpAndDoesNotReplaceAppliedAt() throws Exception { + IssuerGenerationAuthorityEvent applied = event("2", "3", "4", 8, ISSUER_ID); + Map existing = bootstrapProjection("3", "4", "2", applied); + SourceReadback readback = readback(ISSUER_ID, "3", "4", "2", applied, applied); + + IssuerAuthorityProjectionTransitions.NoOp decision = + (IssuerAuthorityProjectionTransitions.NoOp) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "ignored-for-no-op"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.EXACT_DUPLICATE); + assertThat(existing).containsEntry("appliedAt", "stable-time"); + } + + @Test + void duplicateWithDifferentCompleteCanonicalEventQuarantines() throws Exception { + IssuerGenerationAuthorityEvent applied = event("1", "2", "2", 9, ISSUER_ID); + Map existing = bootstrapProjection("2", "2", "1", applied); + IssuerGenerationAuthorityEvent conflicting = event("1", "2", "2", 10, ISSUER_ID); + IssuerGenerationAuthorityEvent current = event("2", "3", "3", 11, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "3", "3", "2", current, conflicting); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.DUPLICATE_EVENT_CONFLICT); + assertThat(existing).containsEntry("lastAppliedSourceOutboxSequence", "1"); + } + + @Test + void authenticatedHistoricalDuplicateMayHaveLowerGenerationAndSourceVersion() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 12, ISSUER_ID); + IssuerGenerationAuthorityEvent later = event("2", "4", "6", 13, ISSUER_ID); + Map existing = bootstrapProjection("4", "6", "2", later); + SourceReadback readback = readback(ISSUER_ID, "4", "6", "2", later, first); + + IssuerAuthorityProjectionTransitions.NoOp decision = + (IssuerAuthorityProjectionTransitions.NoOp) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.VERIFIED_HISTORICAL_DUPLICATE); + } + + @Test + void currentAccountCheckpointRegressionQuarantinesEvenForAContiguousSelectedEvent() + throws Exception { + IssuerGenerationAuthorityEvent installed = event("2", "8", "9", 14, ISSUER_ID); + Map existing = bootstrapProjection("8", "9", "2", installed); + IssuerGenerationAuthorityEvent regressedCurrent = event("3", "7", "8", 15, ISSUER_ID); + SourceReadback readback = + readback(ISSUER_ID, "7", "8", "3", regressedCurrent, regressedCurrent); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); + } + + @Test + void differentIssuerStreamProjectionQuarantines() throws Exception { + String otherIssuer = "https://other.example.test/issuer"; + IssuerGenerationAuthorityEvent otherEvent = event("1", "2", "3", 16, otherIssuer); + Map existing = bootstrapProjection(otherIssuer, "2", "3", "1", otherEvent); + IssuerGenerationAuthorityEvent current = event("1", "2", "3", 17, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "2", "3", "1", current, current); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.ISSUER_OR_STREAM_CHANGED); + } + + @Test + void countersBeyondLongRemainExactAndNoSequenceGenerationEquationIsAssumed() throws Exception { + BigInteger sequence = new BigInteger("922337203685477580812345678901234567891"); + BigInteger priorSequence = sequence.subtract(BigInteger.ONE); + String generation = "800000000000000000000000000000000000001"; + BigInteger priorVersion = new BigInteger("800000000000000000000000000000000000010"); + String version = priorVersion.add(BigInteger.ONE).toString(); + IssuerGenerationAuthorityEvent prior = + event(priorSequence.toString(), generation, priorVersion.toString(), 18, ISSUER_ID); + Map existing = + bootstrapProjection(generation, priorVersion.toString(), priorSequence.toString(), prior); + IssuerGenerationAuthorityEvent next = + event(sequence.toString(), generation, version, 19, ISSUER_ID); + SourceReadback readback = + readback(ISSUER_ID, generation, version, sequence.toString(), next, next); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(mutation.nextProjection()) + .containsEntry("lastAppliedSourceOutboxSequence", sequence.toString()) + .containsEntry("issuerAuthGeneration", generation) + .containsEntry("sourceEventId", next.eventId()); + } + + private static Map bootstrapProjection( + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest) + throws Exception { + return bootstrapProjection(ISSUER_ID, generation, sourceVersion, sequence, latest); + } + + private static Map bootstrapProjection( + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest) + throws Exception { + SourceReadback readback = readback(issuerId, generation, sourceVersion, sequence, latest, null); + return ((IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time")) + .nextProjection(); + } + + private static SourceReadback readback( + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest, + IssuerGenerationAuthorityEvent selected) + throws Exception { + String sourceScope = "issuer/" + issuerId; + String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(sourceScope) + .setOutboxStreamKey(streamKey) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latest != null) { + snapshot.setLatestEventCanonicalJson(latest.canonicalJson()); + } + ReadIssuerAuthorityForRuntimeResponse.Builder response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(NAMESPACE) + .setRequestId(QUERY_ID) + .setSourceSnapshot(snapshot.build()); + if (selected != null) { + response.setRequestedEventCanonicalJson(selected.canonicalJson()); + } + + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response.build()); + AccountIssuerAuthorityClient client = newClient(stub, issuerId); + if (selected == null) { + return client.readCurrent(QUERY_ID); + } + return client.readCommittedEvent(QUERY_ID, selected.outboxSequence()); + } + + private static IssuerGenerationAuthorityEvent event( + String sequence, String generation, String sourceVersion, int identity, String issuerId) { + String requestId = String.format(Locale.ROOT, "00000000-0000-4000-8000-%012d", identity); + String scope = "issuer/" + issuerId; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", EVENT_ID_PREFIX + requestId, + "requestId", requestId, + "issuerId", issuerId, + "sourceScope", scope, + "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, + "outboxSequence", sequence, + "issuerAuthGeneration", generation, + "sourceVersion", sourceVersion)); + } + + private static AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, String issuerId) + throws Exception { + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + issuerId); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + return tls; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java new file mode 100644 index 0000000000..452361d460 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java @@ -0,0 +1,158 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.core.RedisTemplate; + +class RedisIssuerAuthorityProjectionStoreTest { + private static final String COORD_PASSWORD = "coordination-secret"; + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String REQUEST_ID = "11111111-1111-4111-8111-111111111111"; + + @Test + void requiresExactCoordinationPrincipalAndCredentials() { + assertThatThrownBy( + () -> + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_cache_app", COORD_PASSWORD)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("gamesession_coord_app"); + assertThatThrownBy( + () -> + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_coord_app", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("credential"); + } + + @Test + void rejectsNormalizedCoordinationAndCacheEndpointCollision() { + var coordination = + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + "redis-coord.internal.", 6379, "gamesession_coord_app", COORD_PASSWORD); + var cache = + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( + "REDIS-COORD.INTERNAL", 6379); + + assertThatThrownBy(() -> new RedisIssuerAuthorityProjectionStore("test", coordination, cache)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("endpoints must be distinct"); + } + + @Test + void constructorRequiresBothTypedRoleEndpointsWithoutOpeningRedis() { + var store = + new RedisIssuerAuthorityProjectionStore( + "test", + coordination("coordination.internal", 6379), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("cache.internal", 6379)); + + assertThatThrownBy(() -> store.apply(null, "stable-time")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicit init()"); + store.close(); + } + + @Test + void wrongSourceNamespaceIsRejectedBeforeAnyRedisCommand() throws Exception { + RedisIssuerAuthorityProjectionStore store = + new RedisIssuerAuthorityProjectionStore( + "other", + coordination("127.0.0.1", 1), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("127.0.0.1", 2)); + store.init(); + + try { + var result = store.apply(sourceReadback("test"), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("ACCOUNT_NAMESPACE_MISMATCH"); + } finally { + store.close(); + } + } + + @Test + void coordinationCredentialIsRedactedAndNoAmbientRedisTemplateConstructorExists() + throws Exception { + var endpoint = coordination("coordination.internal", 6379); + + assertThat(endpoint.toString()).contains("password=").doesNotContain(COORD_PASSWORD); + boolean acceptsAmbientTemplate = + Arrays.stream(RedisIssuerAuthorityProjectionStore.class.getConstructors()) + .anyMatch( + constructor -> + Arrays.stream(constructor.getParameterTypes()) + .anyMatch(RedisTemplate.class::isAssignableFrom)); + assertThat(acceptsAmbientTemplate).isFalse(); + } + + private static RedisIssuerAuthorityProjectionStore.CoordinationEndpoint coordination( + String host, int port) { + return new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + host, port, "gamesession_coord_app", COORD_PASSWORD); + } + + private static SourceReadback sourceReadback(String targetNamespace) throws Exception { + String scope = "issuer/" + ISSUER_ID; + IssuerAuthoritySourceSnapshot snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(ISSUER_ID) + .setSourceScope(scope) + .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) + .setIssuerAuthGeneration("1") + .setSourceVersion("1") + .setOutboxSequence("0") + .build(); + ReadIssuerAuthorityForRuntimeResponse response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(targetNamespace) + .setRequestId(REQUEST_ID) + .setSourceSnapshot(snapshot) + .build(); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + tls, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + "test", + ISSUER_ID); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client.readCurrent(REQUEST_ID); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 4894fe1e4e..65b4497aa6 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -7,6 +7,9 @@ rootProject.name = "firemud" include("common-data-runtime") project(":common-data-runtime").projectDir = File("services/common-data-runtime") +include("common-redis-contracts") +project(":common-redis-contracts").projectDir = File("services/common-redis-contracts") + include("common-platform-core") project(":common-platform-core").projectDir = File("services/common-platform-core") From 9d62089e5351ae3f2fe320697bab682bfc0f220a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:09:34 +1300 Subject: [PATCH 13/22] Align WebSocket integration fixture with retained tenant UUID authority --- ...essionWebSocketHandlerIntegrationTest.java | 134 +++++++++++++++++- 1 file changed, 132 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 33d16a27f5..c56cf84b7e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -15,10 +15,13 @@ import java.net.URI; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.Signature; import java.time.Clock; import java.time.Instant; +import java.util.Base64; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -29,12 +32,14 @@ import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamelogic.v1.LookResult; import net.firedevops.firemud.gamesession.GameSessionServiceApplication; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; import net.firedevops.firemud.gamesession.client.GameLogicClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; @@ -42,6 +47,9 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; @@ -50,7 +58,9 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.test.GameInstanceTestFixtures; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; @@ -64,6 +74,7 @@ import net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; +import org.jooq.DSLContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -77,10 +88,14 @@ import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHttpHeaders; import org.testcontainers.containers.PostgreSQLContainer; @@ -98,6 +113,7 @@ "firemud.database.enabled=true", "spring.data.redis.repositories.enabled=false", "spring.application.name=game-session-service", + "firemud.grpc.workload-namespace=websocket-handler-retained-tenant-test", "spring.grpc.server.port=0", "spring.flyway.enabled=true", "firemud.gameplay.catalog.worlds[0].slug=demo", @@ -123,6 +139,14 @@ @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionWebSocketHandlerIntegrationTest { private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String TEST_WORKLOAD_NAMESPACE = "websocket-handler-retained-tenant-test"; + private static final long RETAINED_TENANT_ID = 22L; + private static final UUID CANONICAL_TENANT_UUID = + UUID.fromString("b80e5c4d-a732-4e99-9126-dfe151cae8e5"); + private static final UUID SYNTHETIC_APPROVAL_OPERATION_ID = + UUID.fromString("301a8ed5-a6c1-4b29-b61f-e1487dc2a190"); + private static final UUID SYNTHETIC_ASSOCIATION_REQUEST_ID = + UUID.fromString("61691c55-76b0-48df-a2a1-20a0148f693a"); // Runtime target 2 belongs to the sandbox route in this fixture. private static final long CUTOVER_GAME_INSTANCE_ID = 3L; @@ -182,6 +206,16 @@ static void registerProperties(DynamicPropertyRegistry registry) { @Autowired private GameplayAdmissionPointerEventRepository gameplayAdmissionPointerEventRepository; + @Autowired private DSLContext dsl; + + @Autowired private GameSessionRetainedTenantSnapshotRepository retainedTenantSnapshotRepository; + + @Autowired private PlatformTransactionManager transactionManager; + + @Autowired private JdbcTemplate jdbcTemplate; + + @Autowired private RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver; + private final ConcurrentMap redisValueStore = new ConcurrentHashMap<>(); private final ConcurrentMap> redisSetStore = new ConcurrentHashMap<>(); @@ -194,7 +228,12 @@ void setUp() { sessionContextService.deleteBySessionId(22L, 42L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + jdbcTemplate, 1L, RETAINED_TENANT_ID, OWNER_ACCOUNT_UUID, 700L); + GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( + jdbcTemplate, 2L, RETAINED_TENANT_ID, OWNER_ACCOUNT_UUID, 700L); resetAdmissionPointers(); + ensureSyntheticRetainedTenantAssociation(); when(redisTemplate.opsForValue()).thenReturn(redisValueOperations); when(redisTemplate.opsForSet()).thenReturn(redisSetOperations); when(redisValueOperations.get(org.mockito.ArgumentMatchers.anyString())) @@ -268,7 +307,11 @@ void setUp() { net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1"), + .active( + "f2ed193b-12c1-4c96-bcad-c162229af440", + RETAINED_TENANT_ID, + CANONICAL_TENANT_UUID.toString(), + "1"), invocation.getArgument(0))) .when(accountClient) .getTenantMembershipForRuntime( @@ -276,7 +319,7 @@ void setUp() { net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); org.mockito.Mockito.doReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID.toString()) .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) @@ -490,6 +533,17 @@ void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService).enqueue("41", "LOOK", false); + verify(accountClient, atLeastOnce()) + .getTenantEntitlementsForRuntime( + eq(CANONICAL_TENANT_UUID.toString()), + org.mockito.ArgumentMatchers.nullable(String.class)); + verify(accountClient, atLeastOnce()) + .getTenantMembershipForRuntime( + argThat( + request -> + CANONICAL_TENANT_UUID.toString().equals(request.getTenantId()) + && "1".equals(request.getGameInstanceId()) + && "41".equals(request.getSessionId()))); verify(gameLogicClient) .resolveLook( argThat(ctx -> matchesContext(ctx, 22L, 41L, 123L, 1L, "R-1021")), @@ -1079,6 +1133,82 @@ private void performLogoutFlow(String sessionId) throws Exception { } } + private void ensureSyntheticRetainedTenantAssociation() { + Optional existing = + retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(RETAINED_TENANT_ID); + if (existing.isPresent()) { + assertThat(existing).contains(CANONICAL_TENANT_UUID); + return; + } + + GameSessionRetainedTenantAssociationRepository associationRepository = + new GameSessionRetainedTenantAssociationRepository( + dsl, retainedTenantSnapshotRepository, TEST_WORKLOAD_NAMESPACE); + TransactionTemplate ownerTransaction = new TransactionTemplate(transactionManager); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + var snapshot = + java.util.Objects.requireNonNull( + ownerTransaction.execute( + status -> + retainedTenantSnapshotRepository.capture( + TEST_WORKLOAD_NAMESPACE, Long.toString(RETAINED_TENANT_ID))), + "synthetic retained-tenant snapshot must be captured"); + // This signed owner assertion is synthetic test evidence, not a live Game Design approval. + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + 1, + SYNTHETIC_APPROVAL_OPERATION_ID, + TEST_WORKLOAD_NAMESPACE, + "synthetic-websocket-fixture-key", + "synthetic-websocket-fixture", + "synthetic-websocket-test-only", + "2026-01-01T00:00:00Z", + Long.toString(RETAINED_TENANT_ID), + CANONICAL_TENANT_UUID, + "900022", + "websocket-handler-test-fixture", + "NEW_GAME_ROW", + snapshot.evidenceDigest()); + LegacyGameSessionTenantAssociationReceipt approval = syntheticAssociationApproval(evidence); + AssociationReceipt committed = + java.util.Objects.requireNonNull( + ownerTransaction.execute( + status -> + associationRepository.register(SYNTHETIC_ASSOCIATION_REQUEST_ID, approval)), + "synthetic retained-tenant association must commit"); + AssociationReceipt readback = + associationRepository + .read( + committed.operationId(), + SYNTHETIC_ASSOCIATION_REQUEST_ID, + CANONICAL_TENANT_UUID, + RETAINED_TENANT_ID, + TEST_WORKLOAD_NAMESPACE) + .orElseThrow( + () -> new IllegalStateException("Synthetic retained-tenant readback is missing")); + assertThat(readback).isEqualTo(committed); + assertThat(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(RETAINED_TENANT_ID)) + .contains(CANONICAL_TENANT_UUID); + } + + private static LegacyGameSessionTenantAssociationReceipt syntheticAssociationApproval( + GameSessionTenantAssociationEvidence evidence) { + try { + KeyPair keyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Signature signer = Signature.getInstance("Ed25519"); + signer.initSign(keyPair.getPrivate()); + signer.update(evidence.preimage()); + String signature = Base64.getEncoder().encodeToString(signer.sign()); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, evidence.manifestDigest(), signature); + } catch (Exception exception) { + throw new IllegalStateException( + "Could not sign synthetic websocket fixture evidence", exception); + } + } + private void bumpProductionAdmissionPointer( long newGameInstanceId, boolean requiresCharacterSelection) { long expectedPointerVersion = From 933d1f035b44a6b439dc078593c2db506eb38159 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:46:13 +1300 Subject: [PATCH 14/22] Use canonical Account UUID in WebSocket PLAY character fixture --- ...essionWebSocketHandlerIntegrationTest.java | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index c56cf84b7e..4080a443b5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -61,6 +61,7 @@ import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.test.GameInstanceTestFixtures; +import net.firedevops.firemud.gamesession.test.stubs.GameDesignStubServer; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; @@ -75,6 +76,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -154,10 +156,26 @@ class GameSessionWebSocketHandlerIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + private static final GameDesignStubServer gameDesignStub = startGameDesignStub(); + @DynamicPropertySource static void registerProperties(DynamicPropertyRegistry registry) { PostgresBackedServiceTestSupport.registerPostgresService( registry, postgres, "game_session_service"); + registry.add("firemud.services.gameDesignService", gameDesignStub::endpoint); + } + + @AfterAll + static void closeGameDesignStub() { + gameDesignStub.close(); + } + + private static GameDesignStubServer startGameDesignStub() { + try { + return new GameDesignStubServer(0); + } catch (java.io.IOException exception) { + throw new ExceptionInInitializerError(exception); + } } @LocalServerPort private int port; @@ -349,7 +367,10 @@ void setUp() { .build()) .when(entityManagementClient) .listCharactersByAccount( - eq("22"), eq("123"), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + eq("22"), + eq("f2ed193b-12c1-4c96-bcad-c162229af440"), + eq("1"), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(commandService.enqueue(org.mockito.ArgumentMatchers.anyString(), eq("LOGIN"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue( From c17978978c8e01705c0eb0a9fe140edc3c7c8178 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:30:13 +1300 Subject: [PATCH 15/22] Move coherent Redis projection boundary to existing Account source child --- .github/scripts/classify-change-scope.cjs | 2 - .../scripts/classify-change-scope.test.cjs | 21 - .github/workflows/ci.yml | 27 - build.gradle.kts | 20 +- ...dis-execution-with-aggregated-contracts.md | 2 +- .../game-session-service/api-contracts.md | 2 - .../game-session-service/runtime-and-data.md | 2 - design/architecture/repository-structure.md | 3 +- .../system-architecture-redis-lua-patterns.md | 4 +- .../system-architecture-shared-libraries.md | 6 +- .../player-access-and-session.md | 4 +- ...hared-runtime-contracts-and-persistence.md | 4 +- .../common-redis-contracts/build.gradle.kts | 3 - .../contracts/RedisContractRegistry.java | 284 -------- .../contracts/RedisInvocationContract.java | 41 -- .../contracts/RedisScriptDescriptor.java | 264 -------- .../contracts/RedisContractRegistryTest.java | 444 ------------- .../contracts/RedisScriptDescriptorTest.java | 229 ------- .../game-session-service/build.gradle.kts | 1 - ...ssuerAuthorityProjectionRedisContract.java | 104 --- .../IssuerAuthorityProjectionTransitions.java | 610 ------------------ .../RedisIssuerAuthorityProjectionStore.java | 418 ------------ .../redis/issuer_authority_projection_cas.lua | 54 -- ...thorityProjectionRedisIntegrationTest.java | 360 ----------- ...rAuthorityProjectionRedisContractTest.java | 107 --- ...uerAuthorityProjectionTransitionsTest.java | 399 ------------ ...disIssuerAuthorityProjectionStoreTest.java | 158 ----- settings.gradle.kts | 3 - 28 files changed, 19 insertions(+), 3557 deletions(-) delete mode 100644 services/common-redis-contracts/build.gradle.kts delete mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java delete mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java delete mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java delete mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java delete mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java delete mode 100644 services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua delete mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index 4386d34933..e5273bceec 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -17,7 +17,6 @@ const ALL_SERVICES = [ const ALL_MODULES = [ "common-data-runtime", "common-platform-core", - "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -51,7 +50,6 @@ const SHARED_PREFIXES = [ "services/common-library/", "services/common-data-runtime/", "services/common-platform-core/", - "services/common-redis-contracts/", "services/common-saga/", "services/common-temporal/", "services/common-security/", diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 022ea89092..075a679e3f 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -261,27 +261,6 @@ test("shared modules force every Gradle module, including common-temporal", () = assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("hosted-environment-identity-controller")); }); -test("common Redis contracts use shared-library validation without becoming bootable", () => { - const result = classifyChangeScope([ - "services/common-redis-contracts/src/main/java/example/RedisContract.java", - ]); - - assert.equal(result.runAll, true); - assert.deepEqual(result.affectedModules, ALL_MODULES); - assert.equal(result.affectedModules.includes("common-redis-contracts"), true); - assert.equal(result.bootableModules.includes("common-redis-contracts"), false); -}); - -test("root Gradle build and settings changes include common Redis contract validation", () => { - for (const path of ["build.gradle.kts", "settings.gradle.kts"]) { - const result = classifyChangeScope([path]); - - assert.equal(result.runAll, true, path); - assert.equal(result.affectedModules.includes("common-redis-contracts"), true, path); - assert.equal(result.bootableModules.includes("common-redis-contracts"), false, path); - } -}); - test("controller and load-testing changes receive their own module checks", () => { const controllerResult = classifyChangeScope([ "services/hosted-environment-identity-controller/src/main/java/example/Controller.java", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ee54eedce..4068f667fc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,7 +59,6 @@ jobs: const completeModules = [ "common-data-runtime", "common-platform-core", - "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -1056,32 +1055,6 @@ jobs: if-no-files-found: warn retention-days: 7 - - name: Run registered Game Session issuer projection Redis component proof - if: ${{ !cancelled() && matrix.module == 'game-session-service' }} - run: | - ./gradlew :game-session-service:integrationTest \ - --tests integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest \ - -PfullCheck --no-build-cache --no-configuration-cache - bash dev-tools/validation/inspect-test-results.sh \ - --strict \ - --require-suite integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest \ - --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSnapshots()' \ - --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEvidence()' \ - --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#gapAndAuthenticatedOlderDuplicateHaveDistinctNoMutationOutcomes()' \ - --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#staleExpectedBytesAreNonMutatingThroughTheRegisteredOwnerScript()' \ - --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl()' \ - --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration()' \ - game-session-service - - - name: Upload registered issuer projection Redis proof results - if: ${{ always() && matrix.module == 'game-session-service' }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: game-session-issuer-projection-redis-proof-${{ github.sha }} - path: services/game-session-service/build/test-results/integrationTest/TEST-*IssuerAuthorityProjectionRedisIntegrationTest.xml - if-no-files-found: warn - retention-days: 7 - - name: Run Game Session management owner UUID PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/build.gradle.kts b/build.gradle.kts index 4ebde85669..a8832406ea 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -225,17 +225,15 @@ subprojects { dependencies { implementation(platform(libs.findLibrary("spring-boot-dependencies").get())) testImplementation(platform(libs.findLibrary("spring-boot-dependencies").get())) - if (name != "common-redis-contracts") { - implementation(libs.findLibrary("protobuf-java").get()) - implementation(libs.findLibrary("grpc-netty-shaded").get()) - implementation(libs.findLibrary("grpc-protobuf").get()) - implementation(libs.findLibrary("grpc-stub").get()) - implementation("javax.annotation:javax.annotation-api:1.3.2") - testImplementation(libs.findLibrary("spring-boot-starter-test").get()) - testImplementation(libs.findLibrary("spring-boot-starter-restclient-test").get()) - testImplementation(libs.findLibrary("spring-boot-resttestclient").get()) - testImplementation(libs.findLibrary("spring-boot-starter-webmvc-test").get()) - } + implementation(libs.findLibrary("protobuf-java").get()) + implementation(libs.findLibrary("grpc-netty-shaded").get()) + implementation(libs.findLibrary("grpc-protobuf").get()) + implementation(libs.findLibrary("grpc-stub").get()) + implementation("javax.annotation:javax.annotation-api:1.3.2") + testImplementation(libs.findLibrary("spring-boot-starter-test").get()) + testImplementation(libs.findLibrary("spring-boot-starter-restclient-test").get()) + testImplementation(libs.findLibrary("spring-boot-resttestclient").get()) + testImplementation(libs.findLibrary("spring-boot-starter-webmvc-test").get()) testRuntimeOnly(libs.findLibrary("junit-platform-launcher").get()) if (projectDir.parentFile.name == "services" && !name.startsWith("common-")) { testImplementation(testFixtures(project(":common-test-support"))) diff --git a/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md b/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md index f31dda9f8c..4525dd0ad0 100644 --- a/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md +++ b/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is partially implemented. The narrow `common-redis-contracts` module provides immutable descriptors, explicit prefix ownership and invocation validation for role, principal, script identity/digest, key/argument arity and cluster slots. It has no executable owner scripts or automatic runtime wiring. Complete repository aggregation, existing-script/prefix coverage, ownership enforcement, descriptor-driven generic CI, rollout/coexistence evidence and deployed role/ACL proof remain gaps; a selected registered invocation does not establish those global guarantees. Current proof status remains in the [Shared Runtime tracker](../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#capability-status). +This decision is not implemented. The shared Redis-contract foundation, owner-local descriptor contributions, repository aggregation, ownership enforcement, and descriptor-driven proof remain gaps. ## Decision Record diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 970a48b6ad..b92f9995c5 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -10,8 +10,6 @@ Target state makes Game Session the authoritative owner of region/tick coordinat This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: -The dedicated source client, pure issuer-projection transition layer and registered owner-local Redis store remain unwired. The store uses an explicitly initialized Coordination connection rather than ambient Redis templates; it grants no recipient authorization. Executed component proof and remaining delivery, role/ACL, deployment and activation limits belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md); the issuer-projection contract remains owned by [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). - The dedicated `AccountIssuerAuthorityClient` is an unwired source-only consumer candidate for [Account's issuer readback](../account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). It requires file-backed mutual TLS and the exact Account server workload identity, validates current and explicitly selected historical evidence with the shared issuer-event codec, and compares canonical decimal counters without narrowing them. Its transport result is not a recipient membership snapshot, admission or rebind authorization, an installed issuer projection, or a delivered revocation. Runtime activation remains denied until the complete producer, mutual peer authentication, projection and negative proof passes; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records executed and unavailable proof. - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 7bc07415d5..5a6f92d8c3 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,8 +10,6 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- The source-only issuer projection has an unwired decision layer and registered owner-local atomic Redis store. Its private, explicitly initialized Coordination client does not change the existing runtime client cohort or publish a bean; role/ACL deployment, authenticated event delivery and activation are unproved. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records the precise component and proof boundary; [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md) owns the projection semantics. - - Command ingress carries the canonical Account UUID unchanged into V9's `gameplay_command.account_uuid` slot; an absent Account identity does not invent either a UUID or private numeric selector. Existing numeric row evidence is retained without guessed mapping or backfill. Retained-command replay, complete owner/consumer handoff and activation remain unproved; component implementation and proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). - The management-owner correction in [#2929](https://github.com/benhook1013/FireMUD/pull/2929) adds `game_instances.owner_account_uuid` and retains raw numeric owner evidence unchanged and unmapped. New requests and owner-self checks use canonical UUIDs; this supplies neither Account operator-reference/digest authorization nor catalog activation. Current component, PostgreSQL and composed-child proof limits remain in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/repository-structure.md b/design/architecture/repository-structure.md index 33ed4452ad..546b249189 100644 --- a/design/architecture/repository-structure.md +++ b/design/architecture/repository-structure.md @@ -25,7 +25,6 @@ root │ ├── automation-scripting-service/ │ ├── common-data-runtime/ │ ├── common-platform-core/ -│ ├── common-redis-contracts/ │ ├── common-saga/ │ ├── common-security/ │ ├── common-temporal/ @@ -80,7 +79,7 @@ root - `gradle/` – Gradle version catalog, build conventions, and wrapper binaries. - `k8s/` – Kubernetes base manifests, Helm charts, overlays, monitoring configs, network policies, preview/prod support assets, storage/database helpers, Velero backup assets, and Terraform modules for local and production-like clusters. - `protos/` – Versioned gRPC definitions for every service, organized by service and version as described in this directory’s [gRPC API Style & Versioning Guidelines](./system-architecture-grpc.md). -- `services/` – Spring Boot microservices plus the narrowly scoped shared platform/library Gradle modules (`common-data-runtime`, `common-platform-core`, `common-redis-contracts`, `common-saga`, `common-security`, `common-temporal`, `common-test-support`, and `common-web-support`), including Flyway database migration scripts under `services//src/main/resources/db/migration/` and shared saga migrations under `services/common-saga/src/main/resources/db/migration/saga`. SQL-backed services use one explicit `jOOQ + Flyway` persistence model rather than a mixed long-term ORM stack, and long-running durable control-plane workflows use the shared Temporal substrate rather than service-local workflow scaffolding. The initial `common-redis-contracts` descriptor/validation foundation follows ADR 0176; owner-exclusive Redis builders, adapters and executable Lua remain in their service. Complete repository aggregation and legacy script coverage are still open. +- `services/` – Spring Boot microservices plus the narrowly scoped shared platform/library Gradle modules (`common-data-runtime`, `common-platform-core`, `common-saga`, `common-security`, `common-temporal`, `common-test-support`, and `common-web-support`), including Flyway database migration scripts under `services//src/main/resources/db/migration/` and shared saga migrations under `services/common-saga/src/main/resources/db/migration/saga`. SQL-backed services use one explicit `jOOQ + Flyway` persistence model rather than a mixed long-term ORM stack, and long-running durable control-plane workflows use the shared Temporal substrate rather than service-local workflow scaffolding. ADR 0176's future narrow Redis-contract foundation does not make owner-exclusive Redis execution a shared module concern. - `web-client/` – React web application. - `.editorconfig` – Consistent indentation and newline settings across editors. - `.env.sample` – Example environment variables loaded by `docker compose` and the test suites. diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 74e6b566bd..902bd50d01 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -419,9 +419,9 @@ Script changes must be rolled out in a way that respects both AOF replay semanti - `schemaVersion` changes must support every caller and stored-payload version in the evidenced coexistence set; unknown or ambiguous versions, including unproven missing versions, must fail before mutation with `"UNSUPPORTED_SCHEMA_VERSION"` or the equivalent so AOF replay cannot apply effects with mismatched schemas. - When a reset-required change is introduced, operators follow the reset runbooks so that any surviving AOF history for old scripts is discarded for the relevant scope rather than replayed under incompatible semantics. -## Target-State Lua Script Registry and CI Expectations (Partial Implementation) +## Target-State Lua Script Registry and CI Expectations (Not Implemented) -The initial `common-redis-contracts` foundation validates explicitly contributed descriptors and invocation handles, including owner/prefix, role/principal, identity/digest, arity and cluster-slot checks. It does not inventory or register legacy scripts automatically. Complete repository aggregation, ownership enforcement, the generic test harness, all-script CI and deployed role/ACL proof remain target-state gaps. Once delivered, all coordination-related Lua scripts contribute entries to one aggregated **Lua Script Registry**. The shared Redis-contract foundation owns the registry schema and aggregation; each owning service contributes entries and retains executable Lua for exclusive key families. For each script, the registry records: +The registry, validators, ownership enforcement, generic test harness, and CI checks in this section are target state and are not currently implemented. Once delivered, all coordination-related Lua scripts contribute entries to one aggregated **Lua Script Registry**. The shared Redis-contract foundation owns the registry schema and aggregation; each owning service contributes entries and retains executable Lua for exclusive key families. For each script, the registry records: - Script identifier and file path. - Expected `KEYS` and `ARGV` ordering and allowed prefixes (including hash-tag rules). diff --git a/design/architecture/system-architecture-shared-libraries.md b/design/architecture/system-architecture-shared-libraries.md index 425a5b2dc7..3d0d7daf9b 100644 --- a/design/architecture/system-architecture-shared-libraries.md +++ b/design/architecture/system-architecture-shared-libraries.md @@ -6,7 +6,7 @@ FireMUD's microservices share a set of narrowly scoped modules so each service c ## Implementation Status -The current `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so shared code must not synthesize an absent epoch; exact tuple propagation and final enforcement remain implementation and focused-proof gaps at that boundary. The initial `common-redis-contracts` descriptor/validation slice follows [ADR 0176](./decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md); it is opt-in and contains no owner-exclusive execution or automatic Redis client wiring. Complete owner contributions, repository aggregation, ownership enforcement, generic CI and deployed role/ACL proof remain incomplete. Shared proof status belongs to the [Shared Runtime tracker](../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#capability-status); scripting consequences remain in the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). +The current `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so shared code must not synthesize an absent epoch; exact tuple propagation and final enforcement remain implementation and focused-proof gaps at that boundary. The narrow shared Redis-contract foundation, owner-local descriptor contributions, repository aggregation, ownership enforcement, and descriptor-driven proof required by [ADR 0176](./decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md) are not implemented. See the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current status and proof evidence. - `common-saga` adoption is not currently explicit: base service conventions add the dependency broadly, and deployed service configurations expose the Saga Flyway location even for services without a Saga workflow. This can materialize shared Saga tables and repositories outside the adopter boundary; the explicit adopter allowlist and focused conformance proof remain incomplete. @@ -51,7 +51,7 @@ DTO records for common tasks (paging, IDs, basic metadata) live here so services ### Redis Key Naming & Lua Script Helpers -Target-state Redis helpers follow the owner-local execution and aggregated-contract boundary in [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md). The current foundation validates selected contributed descriptors and immutable invocation handles; the full aggregated boundary is not yet implemented. +Target-state Redis helpers must follow the owner-local execution and aggregated-contract boundary in [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md); this boundary is not implemented in the current tree. The target narrow shared Redis-contract module would own the descriptor schema, common outcome types, Redis-role and prefix-owner rules, hash-tag/cluster-slot validation, compatibility metadata rules, and repository registry/test aggregation. It would own executable key builders, invocation machinery, or Lua only for mutations genuinely executed by multiple independently deployed callers. @@ -85,7 +85,7 @@ Shared code is organized as the narrowly scoped Gradle modules currently include The versioned definitions under `protos/` remain the source for generated service stubs; they are not a replacement for the split Java modules. If a module is published for a supported distribution workflow, it retains its module-specific coordinates under the `net.firedevops.firemud` group rather than being folded into one shared runtime artifact. -Redis contracts follow [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md). The narrow `common-redis-contracts` module carries the initial descriptor schema, bounded outcomes and role/owner/principal/slot invocation validation. Owner-exclusive Redis builders, adapters, executable Lua and semantic tests remain in the owning service. Repository aggregation, full legacy registration and deployed caller/ACL proof remain incomplete; presence of this module does not establish them. +Redis contracts follow [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md): a future narrow foundation such as `common-redis-contracts` may carry descriptor schemas, bounded outcomes, role/owner/slot validation, and repository aggregation. Owner-exclusive Redis builders, adapters, executable Lua, and semantic tests remain in the owning service. The foundation is not evidence that this target module or its registry has been implemented. This split-module boundary aligns with the [Shared Runtime, Service Contracts, and Persistence implementation tracking](../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md) record and keeps reuse explicit without globalizing owner-exclusive execution. 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 b28d3d4d0f..5de411d244 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,11 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The prepared [#2933](https://github.com/benhook1013/FireMUD/pull/2933) correction adds an unwired Game Session issuer-projection transition engine and a registered owner-local byte-exact Redis compare-and-set store on an explicitly initialized Coordination connection. It accepts only the dedicated Account client's verified readback for the configured workload namespace, binds the exact issuer/stream/current or historical event evidence, denies gaps and conflicting progress, and atomically updates the projection and checkpoint without TTL. Duplicate verification is non-mutating; old events require Account's exact immutable historical lookup. This derived projection grants neither admission nor rebind authority. The narrow shared Redis descriptor foundation is partial; complete existing-script aggregation, descriptor-driven global CI, client-cohort cutover, deployed role/ACL proof, event delivery and active-binding revocation remain required. The new PostgreSQL-through-socket-mTLS and Redis integration cases are focused component proof, not deployment or runtime activation. +The issuer-source PostgreSQL-through-socket-mTLS cases remain focused source-handoff proof, not deployment or runtime activation. The derived issuer projection and owner-local Redis foundation, including their component proof, are assigned to [#2938](https://github.com/benhook1013/FireMUD/pull/2938). The projection grants no recipient, admission or rebind authority; exact recipient evidence remains required, and event delivery, role/ACL deployment, activation and active-binding revocation remain open. Exact published [CI 36959528382](https://github.com/benhook1013/FireMUD/actions/runs/36959528382) at `58695d165a03f6004236a8a5e27b1a99f1b0eae4` completed with aggregate failure. Raw XML proved all fifteen issuer PostgreSQL, seventeen retained-association and four snapshot cases executed without skips, failures or errors, along with six reset-producer and both required reset-application methods. Five of six socket mTLS cases passed; the missing-client-certificate assertion lost its underlying throwable, so its cause cannot be established from that result. The corrected test observes the certificate rejection directly with explicit trust-only credentials, bounded timeouts, HTTP/2 negotiation and diagnostics. LOGIN/PLAY/LOOK passed; all four remaining TCP chat-output failures were the Game Logic numeric Account validator rejecting the canonical UUID. The local correction preserves exact UUIDs through Game Logic, but Social's numeric sender store still needs its owner migration; a Social stub does not prove persistence or end-to-end delivery. -The corrected combined Redis foundation/Game Logic/Game Session/TCP full checks, Game Session/TCP boot JARs, links and Markdown passed 221 tasks (45 executed, 176 up-to-date), including formatting, Checkstyle, SpotBugs and JaCoCo. Foundation's twenty unit cases and Game Logic's 91 unit/five integration results were reused from their earlier same-code green gate; Game Logic's boot JAR also passed there. Game Session executed 1,850 unit, eighteen integration and seven cross-service cases, with 17/149/35 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. All executed cases were clean, including fourteen transition, three descriptor, five store and six physical socket mTLS cases. Twenty-five CI-classifier cases and the lightweight scope contract passed. All six Redis integration cases and both PostgreSQL/socket test methods skipped locally without Docker; the latter defines three intended runner cases when parameterized execution is enabled. Strict CI requires their execution and captures raw XML. Fresh runner composition, fresh-image/live identity, membership RPC, credential/context/catalog activation and Account key-ring delivery/readiness remain gates; the RPC and credential paths stay denied and the ring mount remains unpublished. Unit 1B is provisional. +At the combined pre-split checkpoint, Game Logic's 91 unit/five integration results and boot JAR passed; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. All executed cases were clean, including the six physical socket mTLS cases. These Game Logic, TCP and source-transport results remain with #2933. Game Session and common Redis foundation/projection counts from that same run are tracked with #2938. The two PostgreSQL/socket composition methods skipped locally without Docker; strict CI requires their execution and captures raw XML. Fresh runner composition, fresh-image/live identity, membership RPC, credential/context/catalog activation and Account key-ring delivery/readiness remain gates; the RPC and credential paths stay denied and the ring mount remains unpublished. Unit 1B is provisional. ### Preceding local checkpoint evidence diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 47da406dcb..69cfc56e02 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -8,8 +8,6 @@ This is a non-normative implementation tracker for shared runtime, service contr The implementation record below summarizes the shared runtime, service-contract, orchestration, persistence, and workflow boundaries represented by this tracker. It distinguishes live implementation from bounded follow-up work; it does not claim that every future service, runtime consumer, or workflow family has already adopted these conventions. -The initial `common-redis-contracts` module implements the ADR 0176 descriptor and selected-invocation validation boundary: explicit owner/principal/role prefix declarations, versioned identity/digest, ordered key/argument arity, immutable invocation handles and Redis Cluster tag/slot checks. It has no Redis client, automatic runtime wiring or shared owner-exclusive executable. Its focused unit tests executed locally; consolidated static checks and the owner adapter's runtime proof are recorded at their actual checkpoint rather than inferred from the descriptor. Full legacy prefix/script inventory, repository aggregation and all-script CI, rollout/coexistence evidence, role-qualified deployment and ACL proof remain required. Existing generic clients are not cut over by introducing this library. - Account V29 now persists one immutable canonical UUID per Account while preserving the numeric local primary key, with explicit migration/insertion provenance and source-row evidence. The Account repository returns and resolves that UUID using exact source-row readback, while external Account carriers and consumers remain numeric; this does not establish a tenant UUID mapping. `:account-service:spotlessJavaCheck` and the focused `AccountLoginAuthModesTest` executed successfully; the focused `AccountRepositoryIntegrationTest` compiled but all 13 cases, including the V29 retained-row, JOIN-operation, and membership-receipt no-loss proof, were skipped because Docker was unavailable. PostgreSQL runtime behavior is therefore not yet verified. The broader `SF-1.2` capability remains partial and its cross-service UUID convergence is still unproved. Account V25, Game Session V2, and Automation V2 schema activation now has a bounded quiescence slice: base/hosted workloads use non-rolling replacement, the trusted dev-demo path recognizes migration-bearing pushes, preserves that runtime database, stops the three Account, Game Session, and Automation writer Deployments, and verifies their Pods are absent; ordinary pushes retain the established clean namespace reset. Redispatch classification uses the exact namespace-manager deployed-head annotation and fails before mutation if the head or Git ancestry is unproven. The Game Session and Automation V2 migrations check their known V1 indexes plus service-specific active-claim/data prerequisites before changing indexes; this status does not claim equivalent migration validation for Account V25. Focused PostgreSQL failure-path tests are added but remain unverified until Docker-backed service tests run. Candidate PR previews that change Flyway migrations fail before namespace recreation because their scoped runtime path cannot prove Postgres PVC provenance or query migration history; trusted post-merge deployment is the activation path. Recovery is roll-forward only. This does not complete the separate retained-row identity and cross-instance PostgreSQL proof recorded below. @@ -85,7 +83,7 @@ The following current-state findings refine the existing partial/drift status; o | `SF-1.2` Identifiers, tenant context, and routing identity primitives | `partial`: Shared request/runtime identity validation and tenant-aware contexts are live, but durable cross-boundary identity still uses numeric forms instead of ADR 0020 scoped UUIDs, and gameplay delegation has not converged on canonical typed unsigned `PlayerExecutionContext`; legacy gameplay-attestation helpers remain wired into gameplay consumers pending removal. | `drift-found`: current context/scope tests prove useful fields but not the accepted workload/context boundary; `GameplaySessionAttestationServiceTest` proves helper token validation/matching only, and no focused consumer-level proof establishes that attestation values cannot authorize delegated work, establish workload identity, or serve as replay authority. | [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md) | [`RequestIdValidation.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/RequestIdValidation.java); [`RuntimeIdentity.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [`SessionContext.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java); [`GameplaySessionAttestationService.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java) | [`RequestIdValidationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/RequestIdValidationTest.java); [`SessionContextTenantAccessTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java); [`GameplaySessionAttestationServiceTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java) | [Player Access](./player-access-and-session.md); [Realm Routing](./realm-routing-and-playable-state.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Migrate durable cross-boundary identifiers to scoped UUIDs with owner/scope validation; converge on one typed unsigned execution context, retain complete scoped validation, and prove it adds no authorization-store round trip; remove the deprecated gameplay-attestation debt, and add focused consumer proof before claiming that it cannot authorize delegated work. | | `SF-1.3` Authentication, authorization, trust, secrets, and certificates | `partial`: JWT propagation/claims, gRPC and HTTP auth interceptors, and mTLS configuration/reload are live, but signing still uses shared HMAC material and canonical certificate-derived workload identity, method caller allowlists, receiver-specific token profiles, issued-token/auth-generation enforcement, and rotation remain incomplete. Legacy gameplay attestations remain wired into gameplay consumers pending removal. | `drift-found`: current JWT/TLS tests prove bounded existing seams but do not prove Account-only asymmetric issuance and JWKS validation, concrete peer-certificate identity, exact per-method workload authorization, receiver-specific token enforcement, or Account-owned auth-generation enforcement; generic HMAC/internal-token behavior remains implementation debt, and no focused consumer-level proof establishes that legacy attestation values cannot authorize delegated work, establish workload identity, or serve as replay authority. | [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md); [security](../../architecture/system-architecture-security.md); [authentication](../../architecture/system-architecture-authentication.md); [ADR 0014](../../architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md); [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md); [ADR 0037](../../architecture/decisions/adr-0037-fail-closed-token-authority-outages-with-bounded-active-gameplay.md); [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) | [`GrpcClientAuth.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java); [`AuthTokenInterceptor.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java); [`ReloadableJwtUtil.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`apps.yaml`](../../../k8s/helm/firemud/templates/apps.yaml) | [`GrpcClientAuthTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java); [`AuthTokenInterceptorTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [`GameplaySessionAttestationServiceTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java); [`AuthConfigTest.java`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AuthConfigTest.java) | [Player Access](./player-access-and-session.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Platform Operations](./platform-operations-and-delivery.md) | Shared signing material reaches workloads beyond Account and multiple workloads can mint locally; validators do not use Account JWKS. Certificate-bound workload identities, default-deny method allowlists, receiver-specific token enforcement, issued-token registry/auth-generation enforcement, generic internal-token removal, and rotation proof are absent. Consumer-level proof that deprecated gameplay-attestation values cannot authorize delegated calls, establish workload identity, or serve as replay authority is also absent; removal remains required. Player-facing readiness stays blocked pending Account-only private signing, asymmetric validator convergence, certificate-derived caller enforcement, monotonic generation projection/validation, phased rotation/compromise proof, and removal of the obsolete gameplay-attestation implementation debt. | | `SF-1.4` Clocks, timestamps, durations, and time semantics | `partial`: The proto time-field guard, explicit wall-clock fields, and tick-relative command/scheduler fields are live; a shared gameplay clock/state API and broad timed-state adoption are not. | `proven` for the naming guard and current tick/time contract seams, not runtime-wide time semantics. | [scheduler and timers](../../architecture/system-architecture-scripting-scheduler-and-timers.md); [runtime execution](../../architecture/system-architecture-scripting-runtime-execution.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [`check-proto-time-fields.py`](../../../dev-tools/validation/check-proto-time-fields.py); [`automation_scripting_service.proto`](../../../protos/automation-scripting/v1/automation_scripting_service.proto); [`TextCommandDefinition.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDefinition.java); [`ActionStateCommandHandler.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) | [`test_check_proto_time_fields.py`](../../../dev-tools/validation/test_check_proto_time_fields.py); [`AuthoredActionCommandHandlerTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [`TickSchedulerTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java) | [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Gameplay](./gameplay-rules-entities-and-effects.md) | Runtime cooldown state, common buff/condition timing, scheduled-effect execution, and richer gameplay-clock APIs remain gaps. The guard proves naming only; no scheduler design decision is made here. | -| `SF-1.5` Shared libraries, interceptors, and contract helpers | `partial`: Split shared platform, data, security, saga and Temporal modules provide live helpers; the opt-in `common-redis-contracts` module adds initial descriptor and selected-invocation validation, not complete Redis adoption. | `drift-found`: focused descriptor tests execute, but repository aggregation, legacy coverage, generic CI and deployed caller/ACL proof remain incomplete. | [shared libraries](../../architecture/system-architecture-shared-libraries.md); [gRPC](../../architecture/system-architecture-grpc.md); [transactions](../../architecture/system-architecture-transactions.md) | [`CommonGrpcServerConfiguration.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/CommonGrpcServerConfiguration.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`CommonTemporalAutoConfiguration.java`](../../../services/common-temporal/src/main/java/net/firedevops/firemud/common/temporal/config/CommonTemporalAutoConfiguration.java); [`RedisContractRegistry.java`](../../../services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java) | [`GrpcTlsReloadPolicyTest.java`](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcTlsReloadPolicyTest.java); [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`CommonSecurityAutoConfigurationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java); [`FiremudWorkflowIdsTest.java`](../../../services/common-temporal/src/test/java/unit/net/firedevops/firemud/common/temporal/FiremudWorkflowIdsTest.java); [`RedisContractRegistryTest.java`](../../../services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Split `common-*` ownership follows the canonical shared-libraries document and ADR 0176. Complete the remaining aggregate catalog, ownership/role-client adoption and focused proof before claiming the shared boundary complete. This row records no new design decision. | +| `SF-1.5` Shared libraries, interceptors, and contract helpers | `partial`: Split shared platform, data, security, saga, and Temporal modules provide live auto-configuration, interceptors, identity, Redis, persistence, and workflow helpers; the broader shared-library substrate is not complete. | `drift-found`: current shared module/interceptor/helper implementation seams are proven, but the shared Redis descriptor/aggregation/helper foundation and descriptor-driven proof remain absent. | [shared libraries](../../architecture/system-architecture-shared-libraries.md); [gRPC](../../architecture/system-architecture-grpc.md); [transactions](../../architecture/system-architecture-transactions.md) | [`CommonGrpcServerConfiguration.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/CommonGrpcServerConfiguration.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`CommonTemporalAutoConfiguration.java`](../../../services/common-temporal/src/main/java/net/firedevops/firemud/common/temporal/config/CommonTemporalAutoConfiguration.java) | [`GrpcTlsReloadPolicyTest.java`](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcTlsReloadPolicyTest.java); [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`CommonSecurityAutoConfigurationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java); [`FiremudWorkflowIdsTest.java`](../../../services/common-temporal/src/test/java/unit/net/firedevops/firemud/common/temporal/FiremudWorkflowIdsTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Split `common-*` module ownership is converged in the canonical shared-libraries document. The shared Redis key/Lua descriptor, aggregation, and helper foundation required by ADR 0176 is not present in this tree; implement and prove that target boundary before completion. This row records no new design decision. | | `SF-2.1` PostgreSQL ownership, schemas, migrations, and retention | `partial`: `jOOQ + Flyway`, owning service schemas, generated access, schema-qualified saga migrations, and several service-local retention sweeps are live. Shared retention-class declarations, cross-service horizon compatibility and blockers, safe-watermark cleanup, holds, and complete focused proof remain unimplemented; one gateway persistence surface also remains unresolved. | `drift-found`: current tests prove bounded jOOQ/Flyway/schema-qualified persistence and service-local retention seams only; they do not prove the SQL-only migration lineage, explicit Saga adopter wiring, historical migration mappings, shared retention contract, or cross-service cleanup safety. | [database migrations](../../architecture/system-architecture-database-migrations.md); [transactions](../../architecture/system-architecture-transactions.md); [scaling and retention](../../architecture/system-architecture-scaling-runbook.md#data-retention-and-high-churn-tables); [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) | [`FiremudJooqConventionsPlugin.kt`](../../../buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt); [`JooqPersistenceSupport.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/persistence/jooq/JooqPersistenceSupport.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`application.yml`](../../../services/game-session-service/src/main/resources/application.yml); [`Game Session V1__baseline.sql`](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [`PlayerCommandHistoryRetentionSweepJob.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryRetentionSweepJob.java); [`DurableResumeTranscriptExpiryJob.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJob.java); [`ScriptOutboxCleanupJob.java`](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptOutboxCleanupJob.java); [`V1__init.sql`](../../../services/spring-cloud-gateway/src/main/resources/db/migration/V1__init.sql) | [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`PostgresBackedServiceTestSupport.java`](../../../services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java); [`SagaPersistenceRepositoryIntegrationTest.java`](../../../services/common-saga/src/test/java/integration/net/firedevops/firemud/common/saga/persistence/SagaPersistenceRepositoryIntegrationTest.java); [`PlayerCommandHistoryRetentionSweepJobTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryRetentionSweepJobTest.java); [`DurableResumeTranscriptExpiryJobTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java); [`ScriptWorkItemServiceImplTest.java`](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java); [`check-flyway-versions.py`](../../../dev-tools/validation/check-flyway-versions.py) | [Game Session](./game-session-runtime-and-tick-coordination.md); [World Runtime](./world-runtime-and-movement.md); [Game Authoring](./game-authoring-publishing-and-activation.md); [Platform Operations](./platform-operations-and-delivery.md) | ADRs 0079-0082 accept the single persistence stack, adopter-local schema ownership, objective compatibility gates, and semantic identifier-migration boundary. The canonical retention contract and operational consequences are owned by ADR 0163 and the scaling runbook; current service-local sweeps do not establish the shared declarations, horizon inequalities and blockers, safe-watermark cleanup, hold handling, or required focused proof. Gateway `V1__init.sql` creates `route_config`, while runtime routes use [`GatewayRouteServiceImpl.java`](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java) with no jOOQ owner; migration compatibility evidence, shared-migration versioning, generic mapping/orchestration, and focused proof remain incomplete. | | `SF-2.2` Redis coordination, caching, rate limiting, and reset semantics | `partial`: Shared Redis configuration, atomic counters, bounded caches, session/presence coordination, rate limiting, replay guards, and tick Lua seams are live; cross-service reset and script conventions are incomplete. | `proven` for the current shared Redis primitives and named coordination/cache/replay adopters, not the whole reset contract. | [Redis](../../architecture/system-architecture-redis.md); [Redis cache](../../architecture/system-architecture-redis-cache.md); [Redis reset and recovery](../../architecture/system-architecture-redis-reset-and-recovery.md); [Redis Lua patterns](../../architecture/system-architecture-redis-lua-patterns.md) | [`RedisProperties.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/RedisProperties.java); [`RedisAtomicOperations.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/redis/RedisAtomicOperations.java); [`RedisSessionContextService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [`tick_commit.lua`](../../../services/game-session-service/src/main/resources/redis/tick_commit.lua); [`GameplayHandshakeFilter.java`](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java) | [`RedisAtomicOperationsTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/redis/RedisAtomicOperationsTest.java); [`RedisSessionContextServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [`RedisMovementEffectIdempotencyServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [`GameplayHandshakeFilterTest.java`](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Platform Operations](./platform-operations-and-delivery.md) | ADRs 0083-0087 accept the no-general-broker boundary, evidence-scoped Lua compatibility, evidence-gated replay/reset, owner-validated cache classes, and isolated-subject rate-limit semantics. Shared key/script descriptors, coexistence evidence, the durable recovery controller and external fence, room-cache validation, and repo-wide rate-limit/outage proof remain incomplete. Auth allowlist, issued-token registry, and authority-generation consumption are also absent; see `SF-1.3`. | | `SF-2.3` Idempotency, outbox, replay, and reconciliation | `partial`: Durable tick/effect ledgers, Redis idempotency/replay, remote-followup reconciliation, Entity nonblank-`effectId` replay and blank-ID denial, and Automation work-item/outbox paths are live; coverage is owner- and domain-bounded. | `drift-found` | [transactions](../../architecture/system-architecture-transactions.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [runtime execution](../../architecture/system-architecture-scripting-runtime-execution.md); [ADR 0083](../../architecture/decisions/adr-0083-no-general-event-broker-until-measured-adoption-gates.md); [ADR 0120](../../architecture/decisions/adr-0120-owner-read-first-control-plane-notifications.md); [scripting control-plane events](../../architecture/system-architecture-scripting-control-plane-events.md) | [`TickBatchExecutionService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [`RedisDurableGameplayReplayService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisDurableGameplayReplayService.java); [`RemoteFollowupRuntimeServiceImpl.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [`EntityMutationEffectReplayService.java`](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java); [`ScriptWorkItemServiceImpl.java`](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java) | [`TickBatchExecutionServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [`RemoteFollowupRuntimeServiceImplTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [`RedisMovementEffectIdempotencyServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [`EntityMutationEffectReplayServiceTest.java`](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java); [`ScriptWorkItemExecutionServiceImplTest.java`](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java) | [Game Session](./game-session-runtime-and-tick-coordination.md); [Gameplay](./gameplay-rules-entities-and-effects.md); [Automation](./automation-and-scheduler-runtime.md); [World Runtime](./world-runtime-and-movement.md) | Entity service/gRPC unit proof covers blank-ID denial but not trusted caller identity, SQL/PostgreSQL uniqueness, concurrent first-apply, operation/target/request conflict rejection, or in-progress-marker recovery. The named tick, follow-up, and Automation work-item tests remain bounded and do not establish a repo-wide outbox contract. Target ownership remains in the linked transactions, scripting execution, and control-plane event documents. | diff --git a/services/common-redis-contracts/build.gradle.kts b/services/common-redis-contracts/build.gradle.kts deleted file mode 100644 index f6727627a1..0000000000 --- a/services/common-redis-contracts/build.gradle.kts +++ /dev/null @@ -1,3 +0,0 @@ -plugins { - `java-library` -} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java deleted file mode 100644 index 588fa2e818..0000000000 --- a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java +++ /dev/null @@ -1,284 +0,0 @@ -package net.firedevops.firemud.common.redis.contracts; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** Validates owner declarations and prepares immutable invocation contracts. */ -public final class RedisContractRegistry { - - private static final int REDIS_CLUSTER_SLOT_COUNT = 16384; - private final Map descriptorsById; - - public RedisContractRegistry( - Collection prefixDeclarations, - Collection descriptors) { - Objects.requireNonNull(prefixDeclarations, "prefixDeclarations are required"); - Objects.requireNonNull(descriptors, "descriptors are required"); - if (prefixDeclarations.isEmpty()) { - throw new IllegalArgumentException("at least one owner prefix declaration is required"); - } - - Map byPrefix = new HashMap<>(); - List declarations = new ArrayList<>(prefixDeclarations); - Set uniqueDeclarations = new HashSet<>(); - for (PrefixDeclaration declaration : declarations) { - Objects.requireNonNull(declaration, "prefix declaration is required"); - if (!uniqueDeclarations.add(declaration)) { - throw new IllegalArgumentException( - "duplicate owner prefix declaration: " + declaration.prefix()); - } - PrefixDeclaration existing = byPrefix.putIfAbsent(declaration.prefix(), declaration); - if (existing != null) { - throw new IllegalArgumentException( - "conflicting owner prefix declarations: " + declaration.prefix()); - } - } - rejectOverlappingOwnership(declarations); - - Map byId = new HashMap<>(); - Set resourcePaths = new HashSet<>(); - for (RedisScriptDescriptor descriptor : descriptors) { - Objects.requireNonNull(descriptor, "script descriptor is required"); - if (byId.putIfAbsent(descriptor.scriptId(), descriptor) != null) { - throw new IllegalArgumentException("duplicate script identifier: " + descriptor.scriptId()); - } - if (!resourcePaths.add(descriptor.resourcePath())) { - throw new IllegalArgumentException( - "duplicate script resource path: " + descriptor.resourcePath()); - } - validateDeclaredOwnership(descriptor, byPrefix); - } - - this.descriptorsById = Map.copyOf(byId); - } - - /** - * Validates all supplied invocation metadata before returning a handle. The returned handle is - * declarative only; this registry does not load or execute Redis scripts. - */ - public RedisInvocationContract prepareInvocation(InvocationRequest request) { - Objects.requireNonNull(request, "invocation request is required"); - RedisScriptDescriptor descriptor = descriptorsById.get(request.scriptId()); - if (descriptor == null) { - throw new IllegalArgumentException("unregistered script identifier: " + request.scriptId()); - } - - requireEquals(descriptor.resourcePath(), request.resourcePath(), "script resource path"); - requireEquals(descriptor.sha256(), request.sha256(), "script SHA-256 digest"); - requireEquals(descriptor.owner(), request.owner(), "script owner"); - requireEquals(descriptor.principal(), request.principal(), "Redis principal"); - requireEquals(descriptor.role(), request.role(), "Redis role"); - - if (request.keys().size() != descriptor.keys().size()) { - throw new IllegalArgumentException( - "KEYS arity mismatch: expected " - + descriptor.keys().size() - + ", got " - + request.keys().size()); - } - if (request.arguments().size() != descriptor.arguments().size()) { - throw new IllegalArgumentException( - "ARGV arity mismatch: expected " - + descriptor.arguments().size() - + ", got " - + request.arguments().size()); - } - - Integer commonSlot = null; - String commonTag = null; - for (int index = 0; index < descriptor.keys().size(); index++) { - RedisScriptDescriptor.KeySpec keySpec = descriptor.keys().get(index); - String key = request.keys().get(index); - if (key.isEmpty() - || containsControlCharacter(key) - || !key.startsWith(keySpec.ownedPrefix())) { - throw new IllegalArgumentException( - "KEYS[" + index + "] does not match its declared owner prefix"); - } - - if (keySpec.hashTagDeclaration() == RedisScriptDescriptor.HashTagDeclaration.REQUIRED) { - String tag = extractHashTag(key); - if (tag == null) { - throw new IllegalArgumentException( - "KEYS[" + index + "] is missing a non-empty Redis hash tag"); - } - int slot = clusterSlot(key); - if (commonTag != null && !commonTag.equals(tag)) { - throw new IllegalArgumentException("multi-key invocation uses different Redis hash tags"); - } - if (commonSlot != null && commonSlot != slot) { - throw new IllegalArgumentException("multi-key invocation crosses Redis Cluster slots"); - } - commonTag = tag; - commonSlot = slot; - } - } - - return new RedisInvocationContract(descriptor, request.keys(), request.arguments(), commonSlot); - } - - /** Returns the Redis Cluster slot for a key using the first non-empty {@code {...}} tag. */ - public static int clusterSlot(String key) { - Objects.requireNonNull(key, "key is required"); - byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); - int openingBrace = -1; - int closingBrace = -1; - for (int index = 0; index < keyBytes.length; index++) { - if (keyBytes[index] == '{') { - openingBrace = index; - break; - } - } - if (openingBrace >= 0) { - for (int index = openingBrace + 1; index < keyBytes.length; index++) { - if (keyBytes[index] == '}') { - closingBrace = index; - break; - } - } - } - - byte[] hashInput = keyBytes; - int offset = 0; - int length = keyBytes.length; - if (openingBrace >= 0 && closingBrace > openingBrace + 1) { - offset = openingBrace + 1; - length = closingBrace - openingBrace - 1; - } - int crc = crc16(hashInput, offset, length); - return crc % REDIS_CLUSTER_SLOT_COUNT; - } - - private static void rejectOverlappingOwnership(List declarations) { - for (int leftIndex = 0; leftIndex < declarations.size(); leftIndex++) { - PrefixDeclaration left = declarations.get(leftIndex); - for (int rightIndex = leftIndex + 1; rightIndex < declarations.size(); rightIndex++) { - PrefixDeclaration right = declarations.get(rightIndex); - boolean overlaps = - left.prefix().startsWith(right.prefix()) || right.prefix().startsWith(left.prefix()); - boolean samePrincipalScope = - left.owner().equals(right.owner()) - && left.role() == right.role() - && left.principal().equals(right.principal()); - if (overlaps && !samePrincipalScope) { - throw new IllegalArgumentException( - "overlapping Redis prefixes have conflicting ownership: " - + left.prefix() - + " and " - + right.prefix()); - } - } - } - } - - private static void validateDeclaredOwnership( - RedisScriptDescriptor descriptor, Map prefixDeclarations) { - for (RedisScriptDescriptor.KeySpec key : descriptor.keys()) { - PrefixDeclaration declaration = prefixDeclarations.get(key.ownedPrefix()); - if (declaration == null) { - throw new IllegalArgumentException( - "script " - + descriptor.scriptId() - + " references an unowned prefix: " - + key.ownedPrefix()); - } - if (!declaration.owner().equals(descriptor.owner()) - || declaration.role() != descriptor.role() - || !declaration.principal().equals(descriptor.principal())) { - throw new IllegalArgumentException( - "script " + descriptor.scriptId() + " has a wrong owner, principal, or Redis role"); - } - } - } - - private static String extractHashTag(String key) { - int openingBrace = key.indexOf('{'); - if (openingBrace < 0) { - return null; - } - int closingBrace = key.indexOf('}', openingBrace + 1); - int nestedOpeningBrace = key.indexOf('{', openingBrace + 1); - if (closingBrace <= openingBrace + 1 - || (nestedOpeningBrace >= 0 && nestedOpeningBrace < closingBrace)) { - return null; - } - return key.substring(openingBrace + 1, closingBrace); - } - - private static int crc16(byte[] bytes, int offset, int length) { - int crc = 0; - for (int index = offset; index < offset + length; index++) { - crc ^= (bytes[index] & 0xff) << 8; - for (int bit = 0; bit < 8; bit++) { - crc = (crc & 0x8000) == 0 ? crc << 1 : (crc << 1) ^ 0x1021; - } - crc &= 0xffff; - } - return crc; - } - - private static boolean containsControlCharacter(String value) { - return value.chars().anyMatch(Character::isISOControl); - } - - private static void requireEquals(Object expected, Object actual, String fieldName) { - if (!Objects.equals(expected, actual)) { - throw new IllegalArgumentException( - "invocation " + fieldName + " does not match its registration"); - } - } - - public record PrefixDeclaration( - String owner, RedisScriptDescriptor.RedisRole role, String principal, String prefix) { - public PrefixDeclaration { - Objects.requireNonNull(role, "prefix Redis role is required"); - if (owner == null || !owner.matches("[a-z][a-z0-9-]*")) { - throw new IllegalArgumentException("prefix owner must be a lowercase service identifier"); - } - if (principal == null || !principal.matches("[a-z][a-z0-9_]*")) { - throw new IllegalArgumentException("prefix principal must be a lowercase Redis principal"); - } - if (prefix == null || !prefix.matches("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:")) { - throw new IllegalArgumentException("prefix must be colon-delimited and end with a colon"); - } - } - } - - /** The supplied identity and exact KEYS/ARGV values to validate before any Redis call. */ - public record InvocationRequest( - String scriptId, - String resourcePath, - String sha256, - String owner, - String principal, - RedisScriptDescriptor.RedisRole role, - List keys, - List arguments) { - public InvocationRequest { - keys = immutableValues(keys, "KEYS values are required"); - arguments = immutableValues(arguments, "ARGV values are required"); - } - - public List keys() { - return List.copyOf(keys); - } - - public List arguments() { - return List.copyOf(arguments); - } - - private static List immutableValues(List values, String message) { - if (values == null) { - throw new IllegalArgumentException(message); - } - return List.copyOf(values); - } - } -} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java deleted file mode 100644 index 9e60213b29..0000000000 --- a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.firedevops.firemud.common.redis.contracts; - -import java.util.List; -import java.util.OptionalInt; - -/** Immutable proof that an invocation matched one registered Redis script contract. */ -public final class RedisInvocationContract { - - private final RedisScriptDescriptor descriptor; - private final List keys; - private final List arguments; - private final Integer clusterSlot; - - RedisInvocationContract( - RedisScriptDescriptor descriptor, - List keys, - List arguments, - Integer clusterSlot) { - this.descriptor = descriptor; - this.keys = List.copyOf(keys); - this.arguments = List.copyOf(arguments); - this.clusterSlot = clusterSlot; - } - - public RedisScriptDescriptor descriptor() { - return descriptor; - } - - public List keys() { - return keys; - } - - public List arguments() { - return arguments; - } - - /** Empty when no KEYS entry declared a hash tag. */ - public OptionalInt clusterSlot() { - return clusterSlot == null ? OptionalInt.empty() : OptionalInt.of(clusterSlot); - } -} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java deleted file mode 100644 index f7203482ba..0000000000 --- a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java +++ /dev/null @@ -1,264 +0,0 @@ -package net.firedevops.firemud.common.redis.contracts; - -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.regex.Pattern; - -/** Immutable declaration of one versioned, owner-executed Redis script contract. */ -public record RedisScriptDescriptor( - String scriptId, - String resourcePath, - String sha256, - String owner, - String principal, - RedisRole role, - List keys, - List arguments, - ScriptCategory category, - List outcomes, - ResetSensitivity resetSensitivity, - LossClass lossClass, - String tailLossBehavior, - CompatibilityLevel compatibilityLevel, - List supportedCoexistence, - String legacyPayloadShape) { - - public static final String NO_PAYLOAD_VERSION = "none"; - public static final String LEGACY_PAYLOAD_VERSION = "legacy"; - - private static final Pattern SCRIPT_ID_PATTERN = - Pattern.compile("[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*\\.v[1-9][0-9]*"); - private static final Pattern RESOURCE_PATH_PATTERN = - Pattern.compile("redis/(?:[a-z0-9][a-z0-9_-]*/)*[a-z0-9][a-z0-9_-]*\\.lua"); - private static final Pattern OWNER_PATTERN = Pattern.compile("[a-z][a-z0-9-]*"); - private static final Pattern PRINCIPAL_PATTERN = Pattern.compile("[a-z][a-z0-9_]*"); - private static final Pattern PREFIX_PATTERN = - Pattern.compile("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:"); - private static final Pattern DECLARATION_NAME_PATTERN = Pattern.compile("[a-z][A-Za-z0-9]*"); - private static final Pattern OUTCOME_CODE_PATTERN = Pattern.compile("[A-Z][A-Z0-9_]*"); - private static final Pattern VERSION_PATTERN = Pattern.compile("v[1-9][0-9]*"); - - public RedisScriptDescriptor { - requireMatch(scriptId, SCRIPT_ID_PATTERN, "scriptId must be a supported versioned identifier"); - requireMatch( - resourcePath, - RESOURCE_PATH_PATTERN, - "resourcePath must be a relative redis/ classpath Lua resource path"); - requireMatch(sha256, Pattern.compile("[0-9a-f]{64}"), "sha256 must be 64 lowercase hex digits"); - requireMatch(owner, OWNER_PATTERN, "owner must be a lowercase service identifier"); - requireMatch(principal, PRINCIPAL_PATTERN, "principal must be a lowercase Redis principal"); - Objects.requireNonNull(role, "role is required"); - Objects.requireNonNull(category, "category is required"); - Objects.requireNonNull(resetSensitivity, "resetSensitivity is required"); - Objects.requireNonNull(lossClass, "lossClass is required"); - Objects.requireNonNull(compatibilityLevel, "compatibilityLevel is required"); - - keys = immutableNonEmpty(keys, "KEYS declarations are required"); - arguments = - immutable(arguments, "ARGV declarations are required, including an explicit empty list"); - outcomes = immutableNonEmpty(outcomes, "outcomes are required"); - supportedCoexistence = - immutableNonEmpty( - supportedCoexistence, "supported caller/payload coexistence metadata is required"); - tailLossBehavior = requireDescription(tailLossBehavior, "tailLossBehavior"); - legacyPayloadShape = optionalDescription(legacyPayloadShape, "legacyPayloadShape"); - - Set keyNames = new HashSet<>(); - for (KeySpec key : keys) { - if (!keyNames.add(key.name())) { - throw new IllegalArgumentException("duplicate KEYS declaration name: " + key.name()); - } - } - - Set argumentNames = new HashSet<>(); - for (ArgumentSpec argument : arguments) { - if (!argumentNames.add(argument.name())) { - throw new IllegalArgumentException("duplicate ARGV declaration name: " + argument.name()); - } - } - - Set outcomeCodes = new HashSet<>(); - for (OutcomeSpec outcome : outcomes) { - if (!outcomeCodes.add(outcome.code())) { - throw new IllegalArgumentException("duplicate outcome code: " + outcome.code()); - } - } - - Set combinations = new HashSet<>(); - boolean supportsLegacyPayload = false; - for (SupportedCoexistence combination : supportedCoexistence) { - if (!combinations.add(combination)) { - throw new IllegalArgumentException("duplicate caller/payload coexistence declaration"); - } - supportsLegacyPayload |= combination.payloadVersion().equals(LEGACY_PAYLOAD_VERSION); - } - if (supportsLegacyPayload && legacyPayloadShape == null) { - throw new IllegalArgumentException( - "legacyPayloadShape is required when a versionless payload is supported"); - } - if (!supportsLegacyPayload && legacyPayloadShape != null) { - throw new IllegalArgumentException( - "legacyPayloadShape is only valid when a legacy payload is supported"); - } - - if (keys.size() > 1 - && keys.stream().anyMatch(key -> key.hashTagDeclaration() != HashTagDeclaration.REQUIRED)) { - throw new IllegalArgumentException( - "every KEYS declaration in a multi-key script must require a hash tag"); - } - } - - public List keys() { - return List.copyOf(keys); - } - - public List arguments() { - return List.copyOf(arguments); - } - - public List outcomes() { - return List.copyOf(outcomes); - } - - public List supportedCoexistence() { - return List.copyOf(supportedCoexistence); - } - - public enum RedisRole { - COORDINATION, - CACHE_RATE_LIMIT - } - - public enum HashTagDeclaration { - NOT_REQUIRED, - REQUIRED - } - - public enum ScriptCategory { - TICK_LOCK, - TIMER_QUEUE, - SESSION_CAS, - SESSION_TO_REGION_BRIDGE, - MAINTENANCE, - CACHE, - RATE_LIMIT - } - - public enum OutcomeCategory { - SUCCESS, - REPLAY, - STALE, - VALIDATION_FAILURE, - CONTENTION, - DEFERRAL - } - - public enum MutationEffect { - MUTATING, - NON_MUTATING - } - - public enum ResetSensitivity { - NONE, - SESSION, - REGION, - TENANT, - CLUSTER - } - - /** Work classes from ADR 0058. */ - public enum LossClass { - ACCEPTED_PLAYER_COMMAND, - STAGED_EFFECT_OR_RETRY, - CORRECTNESS_BEARING_TIMER, - LOSSY_TIMER_OR_ADVISORY_HINT, - SESSION_LEASE_CACHE_OR_WAKE_UP, - PREMIUM_FINANCIAL_CROSS_TENANT_OR_UNIQUE_EXTERNAL_EFFECT, - EMPTY_REDIS_COLD_START_OR_RESET - } - - public enum CompatibilityLevel { - COMPATIBLE, - REQUIRES_REGION_RESET, - REQUIRES_TENANT_RESET, - REQUIRES_CLUSTER_RESET - } - - public record KeySpec(String name, String ownedPrefix, HashTagDeclaration hashTagDeclaration) { - public KeySpec { - requireMatch(name, DECLARATION_NAME_PATTERN, "KEYS name must be a supported identifier"); - requireMatch(ownedPrefix, PREFIX_PATTERN, "ownedPrefix must be a colon-delimited key prefix"); - Objects.requireNonNull(hashTagDeclaration, "hashTagDeclaration is required"); - } - } - - public record ArgumentSpec(String name) { - public ArgumentSpec { - requireMatch(name, DECLARATION_NAME_PATTERN, "ARGV name must be a supported identifier"); - } - } - - public record OutcomeSpec(String code, OutcomeCategory category, MutationEffect effect) { - public OutcomeSpec { - requireMatch(code, OUTCOME_CODE_PATTERN, "outcome code must be uppercase and stable"); - Objects.requireNonNull(category, "outcome category is required"); - Objects.requireNonNull(effect, "outcome mutation effect is required"); - if (category != OutcomeCategory.SUCCESS && effect != MutationEffect.NON_MUTATING) { - throw new IllegalArgumentException( - "replay, stale, validation, contention, and deferral outcomes must be non-mutating"); - } - } - } - - /** A caller version and payload version that may coexist for this script version. */ - public record SupportedCoexistence(String callerVersion, String payloadVersion) { - public SupportedCoexistence { - requireMatch(callerVersion, VERSION_PATTERN, "callerVersion must use vN syntax"); - if (!NO_PAYLOAD_VERSION.equals(payloadVersion) - && !LEGACY_PAYLOAD_VERSION.equals(payloadVersion)) { - requireMatch( - payloadVersion, VERSION_PATTERN, "payloadVersion must use vN, none, or legacy"); - } - } - } - - private static void requireMatch(String value, Pattern pattern, String message) { - if (value == null || !pattern.matcher(value).matches()) { - throw new IllegalArgumentException(message); - } - } - - private static String requireDescription(String value, String fieldName) { - if (value == null || value.isBlank() || !value.equals(value.trim())) { - throw new IllegalArgumentException(fieldName + " is required and must be trimmed"); - } - return value; - } - - private static String optionalDescription(String value, String fieldName) { - if (value == null || value.isBlank()) { - return null; - } - if (!value.equals(value.trim())) { - throw new IllegalArgumentException(fieldName + " must be trimmed"); - } - return value; - } - - private static List immutable(List values, String message) { - if (values == null) { - throw new IllegalArgumentException(message); - } - return List.copyOf(values); - } - - private static List immutableNonEmpty(List values, String message) { - List copy = immutable(values, message); - if (copy.isEmpty()) { - throw new IllegalArgumentException(message); - } - return copy; - } -} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java deleted file mode 100644 index 30fe3b8265..0000000000 --- a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java +++ /dev/null @@ -1,444 +0,0 @@ -package net.firedevops.firemud.common.redis.contracts; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Test; - -class RedisContractRegistryTest { - - private static final String ISSUER_PREFIX = "session:game:auth:issuer-generation:v1:"; - private static final String ISSUER_KEY = ISSUER_PREFIX + "current"; - private static final RedisScriptDescriptor ISSUER_DESCRIPTOR = issuerDescriptor(); - - @Test - void preparesRegisteredSingleKeyInvocation() { - RedisInvocationContract invocation = issuerRegistry().prepareInvocation(issuerRequest()); - - assertEquals(ISSUER_DESCRIPTOR, invocation.descriptor()); - assertEquals(List.of(ISSUER_KEY), invocation.keys()); - assertEquals(List.of("12", "13"), invocation.arguments()); - assertTrue(invocation.clusterSlot().isEmpty()); - } - - @Test - void preparesTaggedMultiKeyInvocationAndReportsClusterSlot() { - RedisScriptDescriptor descriptor = tickDescriptor(); - RedisContractRegistry registry = - new RedisContractRegistry( - List.of(prefix("game-session", "gamesession_coord_app", "tick:")), List.of(descriptor)); - RedisContractRegistry.InvocationRequest request = - new RedisContractRegistry.InvocationRequest( - descriptor.scriptId(), - descriptor.resourcePath(), - descriptor.sha256(), - descriptor.owner(), - descriptor.principal(), - descriptor.role(), - List.of("tick:{region-one}:lease", "tick:{region-one}:meta"), - List.of("41")); - - RedisInvocationContract invocation = registry.prepareInvocation(request); - - assertEquals( - RedisContractRegistry.clusterSlot("tick:{region-one}:lease"), - invocation.clusterSlot().orElseThrow()); - assertEquals( - invocation.clusterSlot(), - java.util.OptionalInt.of(RedisContractRegistry.clusterSlot("tick:{region-one}:meta"))); - } - - @Test - void clusterSlotUsesRedisCrc16XmodemKnownVector() { - assertEquals(12739, RedisContractRegistry.clusterSlot("key{123456789}")); - } - - @Test - void rejectsWrongRedisRole() { - assertThrows( - IllegalArgumentException.class, - () -> - issuerRegistry() - .prepareInvocation( - request( - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.CACHE_RATE_LIMIT, - ISSUER_DESCRIPTOR.sha256(), - ISSUER_KEY, - List.of("12", "13")))); - } - - @Test - void rejectsWrongOwner() { - assertThrows( - IllegalArgumentException.class, - () -> - issuerRegistry() - .prepareInvocation( - request( - "account", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - ISSUER_DESCRIPTOR.sha256(), - ISSUER_KEY, - List.of("12", "13")))); - } - - @Test - void rejectsWrongPrincipal() { - assertThrows( - IllegalArgumentException.class, - () -> - issuerRegistry() - .prepareInvocation( - request( - "game-session", - "account_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - ISSUER_DESCRIPTOR.sha256(), - ISSUER_KEY, - List.of("12", "13")))); - } - - @Test - void rejectsWrongDigestAndResourcePath() { - assertThrows( - IllegalArgumentException.class, - () -> { - RedisContractRegistry.InvocationRequest valid = issuerRequest(); - issuerRegistry() - .prepareInvocation( - new RedisContractRegistry.InvocationRequest( - valid.scriptId(), - valid.resourcePath(), - "b".repeat(64), - valid.owner(), - valid.principal(), - valid.role(), - valid.keys(), - valid.arguments())); - }); - assertThrows( - IllegalArgumentException.class, - () -> { - RedisContractRegistry.InvocationRequest valid = issuerRequest(); - issuerRegistry() - .prepareInvocation( - new RedisContractRegistry.InvocationRequest( - valid.scriptId(), - "redis/auth/other.lua", - valid.sha256(), - valid.owner(), - valid.principal(), - valid.role(), - valid.keys(), - valid.arguments())); - }); - } - - @Test - void rejectsUnknownScriptIdentity() { - RedisContractRegistry.InvocationRequest valid = issuerRequest(); - assertThrows( - IllegalArgumentException.class, - () -> - issuerRegistry() - .prepareInvocation( - new RedisContractRegistry.InvocationRequest( - "game-session.issuer-generation.v2", - valid.resourcePath(), - valid.sha256(), - valid.owner(), - valid.principal(), - valid.role(), - valid.keys(), - valid.arguments()))); - } - - @Test - void rejectsUnownedKeyPrefix() { - assertThrows( - IllegalArgumentException.class, - () -> - issuerRegistry() - .prepareInvocation( - request( - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - ISSUER_DESCRIPTOR.sha256(), - "session:game:auth:another-family:key", - List.of("12", "13")))); - } - - @Test - void rejectsMissingAndMalformedRequiredHashTags() { - RedisContractRegistry registry = tickRegistry(); - assertThrows( - IllegalArgumentException.class, - () -> registry.prepareInvocation(tickRequest("tick:lease", "tick:meta"))); - assertThrows( - IllegalArgumentException.class, - () -> registry.prepareInvocation(tickRequest("tick:{}:lease", "tick:{}:meta"))); - assertThrows( - IllegalArgumentException.class, - () -> - registry.prepareInvocation( - tickRequest("tick:{region-one:lease", "tick:{region-one:meta"))); - assertThrows( - IllegalArgumentException.class, - () -> registry.prepareInvocation(tickRequest("tick:{{scope}:lease", "tick:{{scope}:meta"))); - } - - @Test - void rejectsMultiKeyCrossSlotInvocation() { - RedisContractRegistry registry = tickRegistry(); - assertThrows( - IllegalArgumentException.class, - () -> - registry.prepareInvocation( - tickRequest("tick:{region-one}:lease", "tick:{region-two}:meta"))); - } - - @Test - void rejectsKeysAndArgumentsArityMismatch() { - RedisContractRegistry registry = issuerRegistry(); - RedisContractRegistry.InvocationRequest valid = issuerRequest(); - assertThrows( - IllegalArgumentException.class, - () -> - registry.prepareInvocation( - new RedisContractRegistry.InvocationRequest( - valid.scriptId(), - valid.resourcePath(), - valid.sha256(), - valid.owner(), - valid.principal(), - valid.role(), - List.of(), - valid.arguments()))); - assertThrows( - IllegalArgumentException.class, - () -> - registry.prepareInvocation( - new RedisContractRegistry.InvocationRequest( - valid.scriptId(), - valid.resourcePath(), - valid.sha256(), - valid.owner(), - valid.principal(), - valid.role(), - valid.keys(), - List.of("12")))); - } - - @Test - void rejectsDuplicateAndConflictingPrefixOwnership() { - RedisContractRegistry.PrefixDeclaration declaration = - prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX); - assertThrows( - IllegalArgumentException.class, - () -> - new RedisContractRegistry( - List.of(declaration, declaration), List.of(ISSUER_DESCRIPTOR))); - assertThrows( - IllegalArgumentException.class, - () -> - new RedisContractRegistry( - List.of(declaration, prefix("account", "account_coord_app", "session:game:auth:")), - List.of(ISSUER_DESCRIPTOR))); - } - - @Test - void rejectsDescriptorWhoseOwnerPrincipalOrRoleDoesNotOwnItsPrefix() { - RedisScriptDescriptor wrongOwner = - descriptor( - "game-session.issuer-generation.v1", - "redis/auth/issuer_generation.lua", - "a".repeat(64), - "account", - "account_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", - ISSUER_PREFIX, - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of("expectedGeneration", "nextGeneration"), - "tail-loss behavior is explicit"); - - assertThrows( - IllegalArgumentException.class, - () -> - new RedisContractRegistry( - List.of(prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX)), - List.of(wrongOwner))); - } - - @Test - void defensivelyCopiesInvocationInputs() { - RedisContractRegistry registry = issuerRegistry(); - List keys = new ArrayList<>(List.of(ISSUER_KEY)); - List arguments = new ArrayList<>(List.of("12", "13")); - RedisContractRegistry.InvocationRequest request = - new RedisContractRegistry.InvocationRequest( - ISSUER_DESCRIPTOR.scriptId(), - ISSUER_DESCRIPTOR.resourcePath(), - ISSUER_DESCRIPTOR.sha256(), - ISSUER_DESCRIPTOR.owner(), - ISSUER_DESCRIPTOR.principal(), - ISSUER_DESCRIPTOR.role(), - keys, - arguments); - keys.clear(); - arguments.clear(); - - assertEquals(List.of(ISSUER_KEY), request.keys()); - assertEquals(List.of("12", "13"), request.arguments()); - assertThrows(UnsupportedOperationException.class, () -> request.keys().add("other")); - assertThrows(UnsupportedOperationException.class, () -> request.arguments().add("14")); - - RedisInvocationContract invocation = registry.prepareInvocation(request); - - assertEquals(List.of(ISSUER_KEY), invocation.keys()); - assertEquals(List.of("12", "13"), invocation.arguments()); - assertThrows(UnsupportedOperationException.class, () -> invocation.keys().add("other")); - assertFalse(invocation.clusterSlot().isPresent()); - } - - private static RedisContractRegistry issuerRegistry() { - return new RedisContractRegistry( - List.of(prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX)), - List.of(ISSUER_DESCRIPTOR)); - } - - private static RedisContractRegistry tickRegistry() { - return new RedisContractRegistry( - List.of(prefix("game-session", "gamesession_coord_app", "tick:")), - List.of(tickDescriptor())); - } - - private static RedisContractRegistry.InvocationRequest issuerRequest() { - return request( - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - ISSUER_DESCRIPTOR.sha256(), - ISSUER_KEY, - List.of("12", "13")); - } - - private static RedisContractRegistry.InvocationRequest request( - String owner, - String principal, - RedisScriptDescriptor.RedisRole role, - String digest, - String key, - List arguments) { - return new RedisContractRegistry.InvocationRequest( - ISSUER_DESCRIPTOR.scriptId(), - ISSUER_DESCRIPTOR.resourcePath(), - digest, - owner, - principal, - role, - List.of(key), - arguments); - } - - private static RedisContractRegistry.InvocationRequest tickRequest( - String firstKey, String secondKey) { - RedisScriptDescriptor descriptor = tickDescriptor(); - return new RedisContractRegistry.InvocationRequest( - descriptor.scriptId(), - descriptor.resourcePath(), - descriptor.sha256(), - descriptor.owner(), - descriptor.principal(), - descriptor.role(), - List.of(firstKey, secondKey), - List.of("41")); - } - - private static RedisContractRegistry.PrefixDeclaration prefix( - String owner, String principal, String prefix) { - return new RedisContractRegistry.PrefixDeclaration( - owner, RedisScriptDescriptor.RedisRole.COORDINATION, principal, prefix); - } - - private static RedisScriptDescriptor issuerDescriptor() { - return descriptor( - "game-session.issuer-generation.v1", - "redis/auth/issuer_generation_cas.lua", - "a".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuerGeneration", - ISSUER_PREFIX, - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of("expectedGeneration", "nextGeneration"), - "loss closes the issuer scope until authenticated Account reconciliation"); - } - - private static RedisScriptDescriptor tickDescriptor() { - return descriptor( - "game-session.tick-stage.v1", - "redis/tick_stage.lua", - "c".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "lease", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED), - new RedisScriptDescriptor.KeySpec( - "metadata", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)), - List.of("expectedEpoch"), - "lost staged work remains subject to its durable ledger and owner reconciliation"); - } - - private static RedisScriptDescriptor descriptor( - String scriptId, - String resourcePath, - String digest, - String owner, - String principal, - RedisScriptDescriptor.RedisRole role, - List keys, - List argumentNames, - String tailLossBehavior) { - return new RedisScriptDescriptor( - scriptId, - resourcePath, - digest, - owner, - principal, - role, - keys, - argumentNames.stream().map(RedisScriptDescriptor.ArgumentSpec::new).toList(), - RedisScriptDescriptor.ScriptCategory.SESSION_CAS, - List.of( - new RedisScriptDescriptor.OutcomeSpec( - "UPDATED", - RedisScriptDescriptor.OutcomeCategory.SUCCESS, - RedisScriptDescriptor.MutationEffect.MUTATING), - new RedisScriptDescriptor.OutcomeSpec( - "STALE_GENERATION", - RedisScriptDescriptor.OutcomeCategory.STALE, - RedisScriptDescriptor.MutationEffect.NON_MUTATING)), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, - tailLossBehavior, - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none")), - null); - } -} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java deleted file mode 100644 index f06f974337..0000000000 --- a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java +++ /dev/null @@ -1,229 +0,0 @@ -package net.firedevops.firemud.common.redis.contracts; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.List; -import org.junit.jupiter.api.Test; - -class RedisScriptDescriptorTest { - - @Test - void requiresScriptIdentityResourceDigestAndAllMetadata() { - assertThrows( - IllegalArgumentException.class, - () -> descriptor("game-session.issuer.v1", "../issuer.lua", "a".repeat(64))); - assertThrows( - IllegalArgumentException.class, - () -> descriptor("issuer", "redis/issuer.lua", "a".repeat(64))); - assertThrows( - IllegalArgumentException.class, - () -> descriptor("game-session.issuer.v1", "redis/issuer.lua", "bad-digest")); - assertThrows( - IllegalArgumentException.class, - () -> descriptor("game-session.issuer.v1", "redis/issuer.lua", "a".repeat(64), " ")); - } - - @Test - void rejectsDuplicateKeyAndArgumentDeclarations() { - assertThrows( - IllegalArgumentException.class, - () -> - new RedisScriptDescriptor( - "game-session.issuer.v1", - "redis/issuer.lua", - "a".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", - "session:auth:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED), - new RedisScriptDescriptor.KeySpec( - "issuer", - "session:auth:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of(new RedisScriptDescriptor.ArgumentSpec("expected")), - category(), - outcomes(), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - lossClass(), - "loss behavior is explicit", - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - coexistence(), - null)); - assertThrows( - IllegalArgumentException.class, - () -> - new RedisScriptDescriptor( - "game-session.issuer.v1", - "redis/issuer.lua", - "a".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", - "session:auth:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of( - new RedisScriptDescriptor.ArgumentSpec("expected"), - new RedisScriptDescriptor.ArgumentSpec("expected")), - category(), - outcomes(), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - lossClass(), - "loss behavior is explicit", - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - coexistence(), - null)); - } - - @Test - void requiresOutcomesAndCallerPayloadCoexistence() { - assertThrows( - IllegalArgumentException.class, - () -> - new RedisScriptDescriptor( - "game-session.issuer.v1", - "redis/issuer.lua", - "a".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", - "session:auth:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of(), - category(), - List.of(), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - lossClass(), - "loss behavior is explicit", - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - coexistence(), - null)); - assertThrows( - IllegalArgumentException.class, - () -> - new RedisScriptDescriptor( - "game-session.issuer.v1", - "redis/issuer.lua", - "a".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", - "session:auth:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of(), - category(), - outcomes(), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - lossClass(), - "loss behavior is explicit", - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - List.of(), - null)); - } - - @Test - void requiresExplicitLegacyPayloadShapeAndNonMutatingFailureOutcomes() { - assertThrows( - IllegalArgumentException.class, - () -> - new RedisScriptDescriptor( - "game-session.issuer.v1", - "redis/issuer.lua", - "a".repeat(64), - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", - "session:auth:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of(), - category(), - outcomes(), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - lossClass(), - "loss behavior is explicit", - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "legacy")), - null)); - assertThrows( - IllegalArgumentException.class, - () -> - new RedisScriptDescriptor.OutcomeSpec( - "INVALID_ARGS", - RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, - RedisScriptDescriptor.MutationEffect.MUTATING)); - } - - @Test - void descriptorListAccessorsRemainImmutable() { - RedisScriptDescriptor descriptor = - descriptor("game-session.issuer.v1", "redis/issuer.lua", "a".repeat(64)); - - assertThrows(UnsupportedOperationException.class, () -> descriptor.keys().clear()); - assertThrows(UnsupportedOperationException.class, () -> descriptor.arguments().clear()); - assertThrows(UnsupportedOperationException.class, () -> descriptor.outcomes().clear()); - assertThrows( - UnsupportedOperationException.class, () -> descriptor.supportedCoexistence().clear()); - } - - private static RedisScriptDescriptor descriptor(String id, String path, String digest) { - return descriptor(id, path, digest, "loss behavior is explicit"); - } - - private static RedisScriptDescriptor descriptor( - String id, String path, String digest, String tailLoss) { - return new RedisScriptDescriptor( - id, - path, - digest, - "game-session", - "gamesession_coord_app", - RedisScriptDescriptor.RedisRole.COORDINATION, - List.of( - new RedisScriptDescriptor.KeySpec( - "issuer", "session:auth:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - List.of(), - category(), - outcomes(), - RedisScriptDescriptor.ResetSensitivity.CLUSTER, - lossClass(), - tailLoss, - RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, - coexistence(), - null); - } - - private static RedisScriptDescriptor.ScriptCategory category() { - return RedisScriptDescriptor.ScriptCategory.SESSION_CAS; - } - - private static List outcomes() { - return List.of( - new RedisScriptDescriptor.OutcomeSpec( - "UPDATED", - RedisScriptDescriptor.OutcomeCategory.SUCCESS, - RedisScriptDescriptor.MutationEffect.MUTATING)); - } - - private static RedisScriptDescriptor.LossClass lossClass() { - return RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP; - } - - private static List coexistence() { - return List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none")); - } -} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 73b780434a..81a8bd7842 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -50,7 +50,6 @@ dependencies { implementation(libs.spring.boot.starter.websocket) implementation(project(":common-saga")) implementation(project(":common-security")) - implementation(project(":common-redis-contracts")) implementation(libs.jjwt.api) runtimeOnly(libs.jjwt.impl) runtimeOnly(libs.jjwt.jackson) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java deleted file mode 100644 index 59bbf8210b..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import java.util.List; -import java.util.Objects; -import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry; -import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; -import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.PrefixDeclaration; -import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; - -/** Registered single-key coordination contract for Game Session's issuer projection. */ -public final class IssuerAuthorityProjectionRedisContract { - public static final String SCRIPT_ID = "game-session.issuer-authority-projection.v1"; - public static final String RESOURCE_PATH = "redis/issuer_authority_projection_cas.lua"; - public static final String OWNER = "game-session-service"; - public static final String PRINCIPAL = "gamesession_coord_app"; - public static final RedisRole ROLE = RedisRole.COORDINATION; - public static final String PROJECTION_SCHEMA_VERSION = - IssuerAuthorityProjectionTransitions.SCHEMA_VERSION; - public static final String KEY_PREFIX = IssuerAuthorityProjectionTransitions.KEY_PREFIX; - - private static final String RESOURCE_SHA256 = - "1c1df7fdf6edc42a9e3ad5dfd5a0db7c33295b41a9e5c28df2a65e98d9069c16"; - private static final RedisScriptDescriptor DESCRIPTOR = createDescriptor(); - private static final RedisContractRegistry REGISTRY = - new RedisContractRegistry( - List.of(new PrefixDeclaration(OWNER, ROLE, PRINCIPAL, KEY_PREFIX)), List.of(DESCRIPTOR)); - - private IssuerAuthorityProjectionRedisContract() {} - - public static RedisScriptDescriptor descriptor() { - return DESCRIPTOR; - } - - /** Declarative registry only; executable access remains private to the typed owner store. */ - public static RedisContractRegistry registry() { - return REGISTRY; - } - - public static String keyForIssuer(String issuerId) { - Objects.requireNonNull(issuerId, "exact issuer ID is required"); - if (issuerId.isBlank() || issuerId.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException( - "exact issuer ID must be nonblank and contain no controls"); - } - return KEY_PREFIX + issuerId; - } - - static RedisInvocationContract prepareInvocation( - String key, String expectedMode, String expectedBytes, String candidateBytes) { - return REGISTRY.prepareInvocation( - new InvocationRequest( - SCRIPT_ID, - RESOURCE_PATH, - RESOURCE_SHA256, - OWNER, - PRINCIPAL, - ROLE, - List.of(key), - List.of(expectedMode, expectedBytes, candidateBytes))); - } - - private static RedisScriptDescriptor createDescriptor() { - return new RedisScriptDescriptor( - SCRIPT_ID, - RESOURCE_PATH, - RESOURCE_SHA256, - OWNER, - PRINCIPAL, - ROLE, - List.of(new KeySpec("issuerProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)), - List.of( - new ArgumentSpec("expectedMode"), - new ArgumentSpec("expectedBytes"), - new ArgumentSpec("candidateBytes")), - ScriptCategory.SESSION_CAS, - List.of( - new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), - new OutcomeSpec("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), - new OutcomeSpec("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), - new OutcomeSpec( - "INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), - new OutcomeSpec( - "TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)), - ResetSensitivity.CLUSTER, - LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, - "On loss, quarantine this issuer scope until an authenticated exact Account checkpoint is reconciled; never admit from this projection.", - CompatibilityLevel.COMPATIBLE, - List.of(new SupportedCoexistence("v1", "v1")), - null); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java deleted file mode 100644 index d55623afe1..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java +++ /dev/null @@ -1,610 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -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.IssuerGenerationAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceSnapshot; - -/** Pure decision layer for the derived Game Session issuer-authority projection. */ -public final class IssuerAuthorityProjectionTransitions { - public static final String KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; - public static final String SCHEMA_VERSION = "game-session-auth-issuer-projection/v1"; - - private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; - private static final BigInteger ZERO = BigInteger.ZERO; - private static final BigInteger ONE = BigInteger.ONE; - - private static final Set BASE_FIELDS = - Set.of( - "schemaVersion", - "issuerId", - "issuerAuthGeneration", - "lastAppliedSourceOutboxSequence", - "sourceOutboxStreamKey", - "appliedAt", - "appliedSourceEvidence"); - private static final Set POSITIVE_FIELDS = Set.of("sourceEventId", "sourceEventDigest"); - - private IssuerAuthorityProjectionTransitions() {} - - /** - * Creates an initial projection only from Account's complete authenticated current readback. - * Sequence zero is source absence evidence; it is not recipient admission evidence. - */ - public static Decision bootstrap(SourceReadback currentReadback, String appliedAt) { - try { - VerifiedReadback readback = verifyReadback(currentReadback); - if (readback.selectedEvent().isPresent()) { - return new Quarantine( - Optional.empty(), QuarantineReason.BOOTSTRAP_REQUIRES_CURRENT_READBACK); - } - requireAppliedAt(appliedAt); - return new Mutation( - Optional.empty(), projectionFor(readback.snapshot(), appliedAt), MutationKind.BOOTSTRAP); - } catch (EvidenceRejected rejected) { - return new Quarantine(Optional.empty(), rejected.reason()); - } catch (IllegalArgumentException malformed) { - return new Quarantine(Optional.empty(), QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - } - - /** - * Decides whether one Account-authenticated selected source event advances, duplicates, or - * contradicts the observed projection. The expected fields and next projection are immutable - * compare-and-set evidence; this method performs no storage operation. - */ - public static Decision decide( - Map observedProjection, SourceReadback sourceReadback, String appliedAt) { - Optional> observed = immutableObserved(observedProjection); - final ExistingProjection existing; - try { - if (observedProjection == null) { - return new Quarantine(Optional.empty(), QuarantineReason.MISSING_EXISTING_PROJECTION); - } - existing = parseExistingProjection(observedProjection); - } catch (IllegalArgumentException malformed) { - return new Quarantine(observed, QuarantineReason.MALFORMED_EXISTING_PROJECTION); - } - - try { - VerifiedReadback readback = verifyReadback(sourceReadback); - if (readback.selectedEvent().isEmpty()) { - return new Quarantine(observed, QuarantineReason.SELECTED_EVENT_REQUIRED); - } - - Checkpoint current = readback.snapshot(); - IssuerGenerationAuthorityEvent selected = readback.selectedEvent().orElseThrow(); - if (!existing.issuerId().equals(current.issuerId()) - || !existing.streamKey().equals(current.streamKey())) { - return new Quarantine(observed, QuarantineReason.ISSUER_OR_STREAM_CHANGED); - } - if (current.sequence().compareTo(existing.sequence()) < 0 - || current.generation().compareTo(existing.generation()) < 0 - || current.sourceVersion().compareTo(existing.sourceVersion()) < 0) { - return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); - } - if (current.sequence().equals(existing.sequence())) { - if (existing.latestEvent() == null) { - if (current.latestEvent() != null - || !current.generation().equals(ONE) - || !current.sourceVersion().equals(ONE)) { - return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_CONFLICT); - } - } else if (current.latestEvent() == null - || !existing - .latestEvent() - .canonicalJson() - .equals(current.latestEvent().canonicalJson())) { - return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_CONFLICT); - } - } else if (current.sourceVersion().compareTo(existing.sourceVersion()) <= 0) { - return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); - } - - BigInteger selectedSequence = positiveDecimal(selected.outboxSequence(), "selected sequence"); - int order = selectedSequence.compareTo(existing.sequence()); - if (order < 0) { - if (positiveDecimal(selected.issuerAuthGeneration(), "selected generation") - .compareTo(existing.generation()) - > 0) { - return new Quarantine(observed, QuarantineReason.HISTORICAL_EVENT_PROGRESS_CONFLICT); - } - if (positiveDecimal(selected.sourceVersion(), "selected source version") - .compareTo(existing.sourceVersion()) - > 0) { - return new Quarantine(observed, QuarantineReason.HISTORICAL_EVENT_PROGRESS_CONFLICT); - } - // The selected event is an exact immutable Account lookup. Historical generations and - // source versions may be lower than the installed later projection. - return new NoOp(NoOpReason.VERIFIED_HISTORICAL_DUPLICATE); - } - - if (order == 0) { - if (existing.latestEvent() == null - || !existing.latestEvent().canonicalJson().equals(selected.canonicalJson())) { - return new Quarantine(observed, QuarantineReason.DUPLICATE_EVENT_CONFLICT); - } - return new NoOp(NoOpReason.EXACT_DUPLICATE); - } - - BigInteger expectedNextSequence = existing.sequence().add(ONE); - if (!selectedSequence.equals(expectedNextSequence)) { - return new Quarantine(observed, QuarantineReason.EVENT_SEQUENCE_GAP); - } - - BigInteger eventGeneration = - positiveDecimal(selected.issuerAuthGeneration(), "selected generation"); - BigInteger eventSourceVersion = - positiveDecimal(selected.sourceVersion(), "selected source version"); - if (eventGeneration.compareTo(existing.generation()) < 0) { - return new Quarantine(observed, QuarantineReason.EVENT_GENERATION_REGRESSED); - } - if (eventSourceVersion.compareTo(existing.sourceVersion()) <= 0) { - return new Quarantine(observed, QuarantineReason.EVENT_SOURCE_VERSION_REGRESSED); - } - requireAppliedAt(appliedAt); - - BigInteger nextGeneration = eventGeneration.max(existing.generation()); - return new Mutation( - observed, - projectionFor( - selected, nextGeneration.toString(), selectedSequence.toString(), appliedAt), - MutationKind.ADVANCE); - } catch (EvidenceRejected rejected) { - return new Quarantine(observed, rejected.reason()); - } catch (IllegalArgumentException malformed) { - return new Quarantine(observed, QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - } - - private static VerifiedReadback verifyReadback(SourceReadback readback) { - if (readback == null - || readback.requestId() == null - || readback.targetNamespace() == null - || readback.targetNamespace().isBlank() - || readback.sourceSnapshot() == null) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - UUID requestId; - try { - requestId = UUID.fromString(readback.requestId()); - } catch (IllegalArgumentException malformed) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - if (new UUID(0L, 0L).equals(requestId) || !requestId.toString().equals(readback.requestId())) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - - Checkpoint snapshot = verifySnapshot(readback.sourceSnapshot()); - Optional selected = readback.requestedEvent(); - if (selected.isPresent()) { - IssuerGenerationAuthorityEvent event = verifyEvent(selected.orElseThrow()); - if (!sameSource(event, snapshot.issuerId(), snapshot.streamKey()) - || positiveDecimal(event.outboxSequence(), "selected sequence") - .compareTo(snapshot.sequence()) - > 0 - || positiveDecimal(event.issuerAuthGeneration(), "selected generation") - .compareTo(snapshot.generation()) - > 0 - || positiveDecimal(event.sourceVersion(), "selected source version") - .compareTo(snapshot.sourceVersion()) - > 0) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - if (snapshot.sequence().equals(positiveDecimal(event.outboxSequence(), "selected sequence")) - && (snapshot.latestEvent() == null - || !snapshot.latestEvent().canonicalJson().equals(event.canonicalJson()))) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - } - return new VerifiedReadback(snapshot, selected); - } - - private static Checkpoint verifySnapshot(SourceSnapshot source) { - if (source == null || source.issuerId() == null || source.issuerId().isBlank()) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - String expectedScope = "issuer/" + source.issuerId(); - String expectedStream = - IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + expectedScope; - if (!expectedScope.equals(source.sourceScope()) - || !expectedStream.equals(source.outboxStreamKey())) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - - BigInteger generation = positiveDecimal(source.issuerAuthGeneration(), "issuer generation"); - BigInteger sourceVersion = positiveDecimal(source.sourceVersion(), "source version"); - BigInteger sequence = nonnegativeDecimal(source.outboxSequence(), "outbox sequence"); - IssuerGenerationAuthorityEvent latest = - source.latestEvent().map(IssuerAuthorityProjectionTransitions::verifyEvent).orElse(null); - if (sequence.equals(ZERO)) { - if (!generation.equals(ONE) || !sourceVersion.equals(ONE) || latest != null) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - } else if (latest == null - || !sameSource(latest, source.issuerId(), source.outboxStreamKey()) - || !sequence.equals(positiveDecimal(latest.outboxSequence(), "latest event sequence")) - || !generation.equals( - positiveDecimal(latest.issuerAuthGeneration(), "latest event generation")) - || !sourceVersion.equals( - positiveDecimal(latest.sourceVersion(), "latest event source version"))) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - return new Checkpoint( - source.issuerId(), source.outboxStreamKey(), generation, sourceVersion, sequence, latest); - } - - private static IssuerGenerationAuthorityEvent verifyEvent( - IssuerGenerationAuthorityEvent supplied) { - if (supplied == null) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - IssuerGenerationAuthorityEvent verified; - try { - verified = IssuerGenerationAuthorityEventV1Codec.verify(supplied.canonicalJson()); - } catch (IllegalArgumentException malformed) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - if (!verified.canonicalJson().equals(supplied.canonicalJson()) - || !verified.eventId().equals(supplied.eventId()) - || !verified.eventDigest().equals(supplied.eventDigest()) - || !verified.issuerId().equals(supplied.issuerId()) - || !verified.sourceScope().equals(supplied.sourceScope()) - || !verified.outboxStreamKey().equals(supplied.outboxStreamKey()) - || !verified.outboxSequence().equals(supplied.outboxSequence()) - || !verified.issuerAuthGeneration().equals(supplied.issuerAuthGeneration()) - || !verified.sourceVersion().equals(supplied.sourceVersion())) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - UUID eventRequestId; - try { - eventRequestId = UUID.fromString(verified.requestId()); - } catch (IllegalArgumentException malformed) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - if (new UUID(0L, 0L).equals(eventRequestId) - || !eventRequestId.toString().equals(verified.requestId()) - || !(EVENT_ID_PREFIX + verified.requestId()).equals(verified.eventId())) { - throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); - } - return verified; - } - - private static boolean sameSource( - IssuerGenerationAuthorityEvent event, String issuerId, String streamKey) { - return issuerId.equals(event.issuerId()) - && ("issuer/" + issuerId).equals(event.sourceScope()) - && streamKey.equals(event.outboxStreamKey()); - } - - private static Map projectionFor(Checkpoint checkpoint, String appliedAt) { - if (checkpoint.sequence().equals(ZERO)) { - return projectionMap( - checkpoint.issuerId(), - checkpoint.generation().toString(), - "0", - checkpoint.streamKey(), - null, - appliedAt, - Map.of()); - } - return projectionFor( - checkpoint.latestEvent(), - checkpoint.generation().toString(), - checkpoint.sequence().toString(), - appliedAt); - } - - private static Map projectionFor( - IssuerGenerationAuthorityEvent event, - String issuerGeneration, - String sequence, - String appliedAt) { - return projectionMap( - event.issuerId(), - issuerGeneration, - sequence, - event.outboxStreamKey(), - event, - appliedAt, - Map.of(sequence, event.canonicalJson())); - } - - private static Map projectionMap( - String issuerId, - String issuerGeneration, - String sequence, - String streamKey, - IssuerGenerationAuthorityEvent latestEvent, - String appliedAt, - Map appliedSourceEvidence) { - Map fields = new LinkedHashMap<>(); - fields.put("schemaVersion", SCHEMA_VERSION); - fields.put("issuerId", issuerId); - fields.put("issuerAuthGeneration", issuerGeneration); - fields.put("lastAppliedSourceOutboxSequence", sequence); - fields.put("sourceOutboxStreamKey", streamKey); - if (latestEvent != null) { - fields.put("sourceEventId", latestEvent.eventId()); - fields.put("sourceEventDigest", latestEvent.eventDigest()); - } - fields.put("appliedAt", appliedAt); - fields.put("appliedSourceEvidence", appliedSourceEvidence); - return immutableMap(fields); - } - - private static ExistingProjection parseExistingProjection(Map supplied) { - if (supplied == null) { - throw new IllegalArgumentException("projection is absent"); - } - String schema = requiredString(supplied, "schemaVersion"); - String issuer = requiredString(supplied, "issuerId"); - String generationText = requiredString(supplied, "issuerAuthGeneration"); - String sequenceText = requiredString(supplied, "lastAppliedSourceOutboxSequence"); - String stream = requiredString(supplied, "sourceOutboxStreamKey"); - String appliedAt = requiredString(supplied, "appliedAt"); - if (!SCHEMA_VERSION.equals(schema) || issuer.isBlank() || appliedAt.isBlank()) { - throw new IllegalArgumentException("projection identity or schema is malformed"); - } - - BigInteger generation = positiveDecimal(generationText, "projection generation"); - BigInteger sequence = nonnegativeDecimal(sequenceText, "projection sequence"); - String expectedStream = - IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuer; - if (!expectedStream.equals(stream)) { - throw new IllegalArgumentException("projection stream identity is malformed"); - } - - Set expectedFields = new java.util.HashSet<>(BASE_FIELDS); - IssuerGenerationAuthorityEvent latest = null; - BigInteger sourceVersion = ONE; - Object evidenceValue = supplied.get("appliedSourceEvidence"); - if (!(evidenceValue instanceof Map evidence)) { - throw new IllegalArgumentException("projection source evidence is malformed"); - } - if (sequence.equals(ZERO)) { - if (!generation.equals(ONE) || !evidence.isEmpty()) { - throw new IllegalArgumentException("zero checkpoint projection is contradictory"); - } - } else { - expectedFields.addAll(POSITIVE_FIELDS); - if (evidence.size() != 1) { - throw new IllegalArgumentException("projection must retain its current source checkpoint"); - } - Object canonicalValue = evidence.get(sequenceText); - if (!(canonicalValue instanceof String canonicalEvent)) { - throw new IllegalArgumentException("projection current source evidence is absent"); - } - latest = verifiedProjectionEvent(canonicalEvent); - if (!sameSource(latest, issuer, stream) - || !sequence.equals(positiveDecimal(latest.outboxSequence(), "projection event sequence")) - || !generation.equals( - positiveDecimal(latest.issuerAuthGeneration(), "projection event generation")) - || !requiredString(supplied, "sourceEventId").equals(latest.eventId()) - || !requiredString(supplied, "sourceEventDigest").equals(latest.eventDigest())) { - throw new IllegalArgumentException("projection event does not match its checkpoint"); - } - sourceVersion = positiveDecimal(latest.sourceVersion(), "projection event source version"); - } - if (!supplied.keySet().equals(expectedFields)) { - throw new IllegalArgumentException("projection fields do not match the declared schema"); - } - validateEvidenceMapKeys(evidence, sequence, sequenceText); - return new ExistingProjection(issuer, generation, sourceVersion, sequence, stream, latest); - } - - private static IssuerGenerationAuthorityEvent verifiedProjectionEvent(String canonicalEvent) { - try { - IssuerGenerationAuthorityEvent event = - IssuerGenerationAuthorityEventV1Codec.verify(canonicalEvent); - if (!event.canonicalJson().equals(canonicalEvent)) { - throw new IllegalArgumentException("projection event is not canonical"); - } - return verifyEvent(event); - } catch (EvidenceRejected rejected) { - throw new IllegalArgumentException("projection event evidence is malformed", rejected); - } - } - - private static void validateEvidenceMapKeys( - Map evidence, BigInteger sequence, String sequenceText) { - for (Map.Entry entry : evidence.entrySet()) { - if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String)) { - throw new IllegalArgumentException("projection applied-source evidence is malformed"); - } - positiveDecimal(key, "projection evidence sequence"); - if (!sequence.equals(ZERO) && !sequenceText.equals(key)) { - throw new IllegalArgumentException("projection evidence is not the current checkpoint"); - } - } - } - - private static String requiredString(Map fields, String name) { - Object value = fields.get(name); - if (!(value instanceof String text)) { - throw new IllegalArgumentException("projection field " + name + " must be a string"); - } - return text; - } - - private static BigInteger positiveDecimal(String value, String label) { - if (value == null || !value.matches("[1-9][0-9]*")) { - throw new IllegalArgumentException(label + " must be a positive canonical decimal"); - } - return new BigInteger(value); - } - - private static BigInteger nonnegativeDecimal(String value, String label) { - if (value == null || !value.matches("(?:0|[1-9][0-9]*)")) { - throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); - } - return new BigInteger(value); - } - - private static void requireAppliedAt(String appliedAt) { - if (appliedAt == null || appliedAt.isBlank()) { - throw reject(QuarantineReason.APPLIED_AT_REQUIRED); - } - } - - private static Optional> immutableObserved(Map observed) { - if (observed == null) { - return Optional.empty(); - } - try { - return Optional.of(immutableMap(observed)); - } catch (IllegalArgumentException malformed) { - return Optional.empty(); - } - } - - private static Map immutableMap(Map source) { - if (source == null) { - throw new IllegalArgumentException("projection maps must not be null"); - } - Map copy = new LinkedHashMap<>(); - for (Map.Entry entry : source.entrySet()) { - if (!(entry.getKey() instanceof String key)) { - throw new IllegalArgumentException("projection map keys must be strings"); - } - copy.put(key, immutableValue(entry.getValue())); - } - return Collections.unmodifiableMap(copy); - } - - private static Object immutableValue(Object value) { - if (value instanceof Map map) { - return immutableMap(map); - } - if (value instanceof List list) { - List copy = new ArrayList<>(list.size()); - for (Object item : list) { - copy.add(immutableValue(item)); - } - return Collections.unmodifiableList(copy); - } - if (value == null - || value instanceof String - || value instanceof Number - || value instanceof Boolean) { - return value; - } - throw new IllegalArgumentException("projection values must be JSON-compatible"); - } - - private static EvidenceRejected reject(QuarantineReason reason) { - return new EvidenceRejected(reason); - } - - private record Checkpoint( - String issuerId, - String streamKey, - BigInteger generation, - BigInteger sourceVersion, - BigInteger sequence, - IssuerGenerationAuthorityEvent latestEvent) {} - - private record VerifiedReadback( - Checkpoint snapshot, Optional selectedEvent) {} - - private record ExistingProjection( - String issuerId, - BigInteger generation, - BigInteger sourceVersion, - BigInteger sequence, - String streamKey, - IssuerGenerationAuthorityEvent latestEvent) {} - - private static final class EvidenceRejected extends RuntimeException { - private static final long serialVersionUID = 1L; - - private final QuarantineReason reason; - - private EvidenceRejected(QuarantineReason reason) { - this.reason = reason; - } - - private QuarantineReason reason() { - return reason; - } - } - - public sealed interface Decision permits Mutation, NoOp, Quarantine {} - - public enum MutationKind { - BOOTSTRAP, - ADVANCE - } - - public enum NoOpReason { - EXACT_DUPLICATE, - VERIFIED_HISTORICAL_DUPLICATE - } - - public enum QuarantineReason { - APPLIED_AT_REQUIRED, - BOOTSTRAP_REQUIRES_CURRENT_READBACK, - CURRENT_CHECKPOINT_CONFLICT, - CURRENT_CHECKPOINT_REGRESSED, - DUPLICATE_EVENT_CONFLICT, - EVENT_GENERATION_REGRESSED, - EVENT_SEQUENCE_GAP, - EVENT_SOURCE_VERSION_REGRESSED, - HISTORICAL_EVENT_PROGRESS_CONFLICT, - ISSUER_OR_STREAM_CHANGED, - MALFORMED_ACCOUNT_READBACK, - MALFORMED_EXISTING_PROJECTION, - MISSING_EXISTING_PROJECTION, - SELECTED_EVENT_REQUIRED - } - - /** An immutable atomic compare-and-set proposal. Empty expected state means bootstrap. */ - public record Mutation( - Optional> expectedProjection, - Map nextProjection, - MutationKind kind) - implements Decision { - public Mutation { - expectedProjection = Objects.requireNonNull(expectedProjection, "expected state is required"); - expectedProjection = - expectedProjection.map(IssuerAuthorityProjectionTransitions::immutableMap); - nextProjection = - immutableMap(Objects.requireNonNull(nextProjection, "next state is required")); - Objects.requireNonNull(kind, "mutation kind is required"); - } - - public Map nextProjection() { - return immutableMap(nextProjection); - } - } - - public record NoOp(NoOpReason reason) implements Decision { - public NoOp { - Objects.requireNonNull(reason, "no-op reason is required"); - } - } - - /** - * Quarantine contains the exact observed state when it could be represented as immutable JSON. - */ - public record Quarantine( - Optional> expectedProjection, QuarantineReason reason) - implements Decision { - public Quarantine { - expectedProjection = Objects.requireNonNull(expectedProjection, "expected state is required"); - expectedProjection = - expectedProjection.map(IssuerAuthorityProjectionTransitions::immutableMap); - Objects.requireNonNull(reason, "quarantine reason is required"); - } - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java deleted file mode 100644 index beedbf3b7c..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java +++ /dev/null @@ -1,418 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.StreamReadFeature; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -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.Duration; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Decision; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Mutation; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.NoOp; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Quarantine; -import org.springframework.core.io.ClassPathResource; -import org.springframework.data.redis.connection.RedisPassword; -import org.springframework.data.redis.connection.RedisStandaloneConfiguration; -import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.script.DefaultRedisScript; - -/** Explicitly owned, unwired Coordination Redis store for the derived issuer projection. */ -public final class RedisIssuerAuthorityProjectionStore implements AutoCloseable { - private static final ObjectMapper JSON = - new ObjectMapper( - JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); - private static final TypeReference> OBJECT_MAP = new TypeReference<>() {}; - private static final DefaultRedisScript CAS_SCRIPT = casScript(); - private static final byte[] CAS_SCRIPT_SHA256 = scriptDigest(); - private static final Duration COMMAND_TIMEOUT = Duration.ofSeconds(3); - - private final String expectedWorkloadNamespace; - private final CoordinationEndpoint coordinationEndpoint; - private final CacheRateLimitEndpoint cacheRateLimitEndpoint; - - private LettuceConnectionFactory connectionFactory; - private StringRedisTemplate redisTemplate; - private boolean closed; - - /** - * Captures explicit role endpoints and credentials. This constructor creates no Spring bean and - * opens no connection; callers must invoke {@link #init()} explicitly. - */ - public RedisIssuerAuthorityProjectionStore( - String expectedWorkloadNamespace, - CoordinationEndpoint coordinationEndpoint, - CacheRateLimitEndpoint cacheRateLimitEndpoint) { - if (!GrpcPeerIdentity.isValidNamespace(expectedWorkloadNamespace)) { - throw new IllegalArgumentException("A valid expected workload namespace is required"); - } - this.expectedWorkloadNamespace = expectedWorkloadNamespace; - this.coordinationEndpoint = - Objects.requireNonNull(coordinationEndpoint, "Coordination endpoint is required"); - this.cacheRateLimitEndpoint = - Objects.requireNonNull(cacheRateLimitEndpoint, "Cache/Rate-Limit endpoint is required"); - validateDistinctEndpoints(coordinationEndpoint, cacheRateLimitEndpoint); - } - - /** Initializes this store's private Coordination-only Lettuce client and String template. */ - public synchronized void init() { - if (closed) { - throw new IllegalStateException("issuer projection store is closed"); - } - if (connectionFactory != null) { - return; - } - verifyScriptDigest(); - - RedisStandaloneConfiguration redisConfiguration = - new RedisStandaloneConfiguration(coordinationEndpoint.host(), coordinationEndpoint.port()); - redisConfiguration.setUsername(coordinationEndpoint.principal()); - redisConfiguration.setPassword(RedisPassword.of(coordinationEndpoint.password())); - LettuceClientConfiguration clientConfiguration = - LettuceClientConfiguration.builder().commandTimeout(COMMAND_TIMEOUT).build(); - - LettuceConnectionFactory newConnectionFactory = - new LettuceConnectionFactory(redisConfiguration, clientConfiguration); - newConnectionFactory.afterPropertiesSet(); - StringRedisTemplate newTemplate = new StringRedisTemplate(newConnectionFactory); - newTemplate.afterPropertiesSet(); - connectionFactory = newConnectionFactory; - redisTemplate = newTemplate; - } - - /** - * Applies one privately verified Account readback. This path performs one exact GET and at most - * one registered owner-script call; it never retries after a stale result. - */ - public synchronized ApplyResult apply(SourceReadback readback, String appliedAt) { - requireInitialized(); - if (readback == null) { - return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); - } - if (!expectedWorkloadNamespace.equals(readback.targetNamespace())) { - return quarantined("ACCOUNT_NAMESPACE_MISMATCH", Optional.empty()); - } - if (readback.sourceSnapshot() == null || readback.sourceSnapshot().issuerId() == null) { - return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); - } - - final String key; - try { - key = - IssuerAuthorityProjectionRedisContract.keyForIssuer(readback.sourceSnapshot().issuerId()); - } catch (IllegalArgumentException malformed) { - return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); - } - - StoredValue observed = readStoredValue(key); - if (observed.bytes() != null && observed.ttlMillis() != -1L) { - return quarantined("TTL_PRESENT", Optional.empty()); - } - - final String observedJson; - final Decision decision; - if (observed.bytes() == null) { - observedJson = null; - decision = IssuerAuthorityProjectionTransitions.bootstrap(readback, appliedAt); - } else { - try { - observedJson = decodeUtf8(observed.bytes()); - Map observedProjection = parseProjection(observedJson); - decision = - IssuerAuthorityProjectionTransitions.decide(observedProjection, readback, appliedAt); - } catch (IOException | IllegalArgumentException malformed) { - return quarantined("MALFORMED_STORED_JSON", Optional.empty()); - } - } - - if (decision instanceof Quarantine quarantine) { - return quarantined(quarantine.reason().name(), Optional.of(decision)); - } - if (decision instanceof NoOp) { - if (observedJson == null) { - return quarantined("NO_OP_WITHOUT_EXISTING_PROJECTION", Optional.of(decision)); - } - String result = executeRegistered(key, "VERIFY", observedJson, ""); - if ("REPLAY".equals(result)) { - return new ApplyResult( - Outcome.NO_OP, - Optional.of(new ProjectionSnapshot(key, observedJson)), - Optional.empty(), - Optional.of(decision)); - } - return mutationOutcome(result, key, observedJson, decision); - } - if (!(decision instanceof Mutation mutation)) { - return quarantined("UNSUPPORTED_TRANSITION_DECISION", Optional.of(decision)); - } - - String expectedMode = observedJson == null ? "ABSENT" : "PRESENT"; - if (mutation.expectedProjection().isPresent() != (observedJson != null)) { - return quarantined("TRANSITION_EXPECTATION_MISMATCH", Optional.of(decision)); - } - String candidateJson; - try { - candidateJson = serializeProjection(mutation.nextProjection()); - } catch (IOException | IllegalArgumentException malformed) { - return quarantined("MALFORMED_CANDIDATE", Optional.of(decision)); - } - String result = - executeRegistered( - key, expectedMode, observedJson == null ? "" : observedJson, candidateJson); - return mutationOutcome(result, key, candidateJson, decision); - } - - @Override - public synchronized void close() { - closed = true; - if (connectionFactory != null) { - connectionFactory.destroy(); - connectionFactory = null; - redisTemplate = null; - } - } - - private ApplyResult mutationOutcome( - String result, String key, String candidateJson, Decision decision) { - if ("APPLIED".equals(result)) { - return new ApplyResult( - Outcome.APPLIED, - Optional.of(new ProjectionSnapshot(key, candidateJson)), - Optional.empty(), - Optional.of(decision)); - } - if ("REPLAY".equals(result)) { - return new ApplyResult( - Outcome.REPLAYED, - Optional.of(new ProjectionSnapshot(key, candidateJson)), - Optional.empty(), - Optional.of(decision)); - } - if ("STALE".equals(result)) { - return new ApplyResult( - Outcome.STALE, Optional.empty(), Optional.empty(), Optional.of(decision)); - } - if ("TTL_PRESENT".equals(result)) { - return quarantined("TTL_PRESENT", Optional.of(decision)); - } - if ("INVALID".equals(result)) { - return quarantined("REGISTERED_SCRIPT_REJECTED_INVOCATION", Optional.of(decision)); - } - return quarantined( - "UNKNOWN_REGISTERED_SCRIPT_RESULT:" + Objects.toString(result, "null"), - Optional.of(decision)); - } - - private String executeRegistered( - String key, String expectedMode, String expectedBytes, String candidateBytes) { - RedisInvocationContract invocation = - IssuerAuthorityProjectionRedisContract.prepareInvocation( - key, expectedMode, expectedBytes, candidateBytes); - RedisScriptDescriptor descriptor = invocation.descriptor(); - if (descriptor != IssuerAuthorityProjectionRedisContract.descriptor() - || !descriptor.scriptId().equals(IssuerAuthorityProjectionRedisContract.SCRIPT_ID) - || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION - || !IssuerAuthorityProjectionRedisContract.PRINCIPAL.equals(descriptor.principal())) { - throw new IllegalStateException( - "issuer projection invocation is not its registered owner contract"); - } - return redisTemplate.execute( - CAS_SCRIPT, List.of(key), expectedMode, expectedBytes, candidateBytes); - } - - private StoredValue readStoredValue(String key) { - byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); - return redisTemplate.execute( - (RedisCallback) - connection -> { - byte[] value = connection.stringCommands().get(keyBytes); - long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); - return new StoredValue(value, ttlMillis); - }); - } - - private static Map parseProjection(String json) throws IOException { - JsonNode root = JSON.readTree(json); - if (root == null || !root.isObject()) { - throw new IllegalArgumentException("stored issuer projection must be a JSON object"); - } - return JSON.convertValue(root, OBJECT_MAP); - } - - private static String serializeProjection(Map projection) throws IOException { - return JSON.writeValueAsString(projection); - } - - private static String decodeUtf8(byte[] value) throws CharacterCodingException { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(value)) - .toString(); - } - - private void requireInitialized() { - if (closed || redisTemplate == null) { - throw new IllegalStateException("issuer projection store requires explicit init()"); - } - } - - private static void validateDistinctEndpoints( - CoordinationEndpoint coordination, CacheRateLimitEndpoint cache) { - if (normalizeHost(coordination.host()).equals(normalizeHost(cache.host())) - && coordination.port() == cache.port()) { - throw new IllegalArgumentException( - "Coordination and Cache/Rate-Limit Redis endpoints must be distinct"); - } - } - - private static String normalizeHost(String host) { - String normalized = host.toLowerCase(Locale.ROOT); - if (normalized.startsWith("[") && normalized.endsWith("]")) { - normalized = normalized.substring(1, normalized.length() - 1); - } - while (normalized.endsWith(".")) { - normalized = normalized.substring(0, normalized.length() - 1); - } - return normalized; - } - - private static DefaultRedisScript casScript() { - DefaultRedisScript script = new DefaultRedisScript<>(); - script.setLocation(new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH)); - script.setResultType(String.class); - return script; - } - - private static byte[] scriptDigest() { - try (var input = - new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH) - .getInputStream()) { - byte[] bytes = input.readAllBytes(); - return MessageDigest.getInstance("SHA-256").digest(bytes); - } catch (IOException exception) { - throw new ExceptionInInitializerError(exception); - } catch (NoSuchAlgorithmException exception) { - throw new ExceptionInInitializerError(exception); - } - } - - private static void verifyScriptDigest() { - String actual = java.util.HexFormat.of().formatHex(CAS_SCRIPT_SHA256); - if (!IssuerAuthorityProjectionRedisContract.descriptor().sha256().equals(actual)) { - throw new IllegalStateException( - "issuer projection Lua resource digest differs from its registration"); - } - } - - private static ApplyResult quarantined(String detail, Optional decision) { - return new ApplyResult(Outcome.QUARANTINED, Optional.empty(), Optional.of(detail), decision); - } - - private record StoredValue(byte[] bytes, long ttlMillis) {} - - public enum Outcome { - APPLIED, - NO_OP, - QUARANTINED, - REPLAYED, - STALE - } - - /** - * Immutable JSON snapshot returned for observation; it grants no admission or rebind authority. - */ - public record ProjectionSnapshot(String key, String json) { - public ProjectionSnapshot { - Objects.requireNonNull(key, "projection key is required"); - Objects.requireNonNull(json, "projection JSON is required"); - } - } - - public record ApplyResult( - Outcome outcome, - Optional snapshot, - Optional detail, - Optional transitionDecision) { - public ApplyResult { - Objects.requireNonNull(outcome, "outcome is required"); - snapshot = Objects.requireNonNull(snapshot, "snapshot optional is required"); - detail = Objects.requireNonNull(detail, "detail optional is required"); - transitionDecision = - Objects.requireNonNull(transitionDecision, "transition decision optional is required"); - } - } - - /** Explicit Coordination endpoint and ACL identity; the principal is not caller-selectable. */ - public record CoordinationEndpoint(String host, int port, String principal, String password) { - public CoordinationEndpoint { - validateHost(host, "Coordination host"); - validatePort(port, "Coordination port"); - if (!IssuerAuthorityProjectionRedisContract.PRINCIPAL.equals(principal)) { - throw new IllegalArgumentException("Coordination principal must be gamesession_coord_app"); - } - if (password == null || password.isBlank()) { - throw new IllegalArgumentException("Coordination ACL credential is required"); - } - } - - @Override - public String toString() { - return "CoordinationEndpoint[host=" - + host - + ", port=" - + port - + ", principal=" - + principal - + ", password=]"; - } - } - - /** Required separate Cache/Rate-Limit endpoint used only for collision validation. */ - public record CacheRateLimitEndpoint(String host, int port) { - public CacheRateLimitEndpoint { - validateHost(host, "Cache/Rate-Limit host"); - validatePort(port, "Cache/Rate-Limit port"); - } - } - - private static void validateHost(String host, String label) { - if (host == null - || host.isBlank() - || !host.equals(host.trim()) - || host.contains("://") - || host.chars().anyMatch(Character::isWhitespace) - || host.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException(label + " must be an explicit host or IP address"); - } - } - - private static void validatePort(int port, String label) { - if (port < 1 || port > 65535) { - throw new IllegalArgumentException(label + " must be between 1 and 65535"); - } - } -} diff --git a/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua b/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua deleted file mode 100644 index a7b32ccc60..0000000000 --- a/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua +++ /dev/null @@ -1,54 +0,0 @@ -if #KEYS ~= 1 or #ARGV ~= 3 then - return 'INVALID' -end - -local mode = ARGV[1] -local expectedBytes = ARGV[2] -local candidateBytes = ARGV[3] - -if mode ~= 'ABSENT' and mode ~= 'PRESENT' and mode ~= 'VERIFY' then - return 'INVALID' -end - -if mode == 'VERIFY' then - if expectedBytes == '' or candidateBytes ~= '' then - return 'INVALID' - end -elseif mode == 'ABSENT' then - if expectedBytes ~= '' or candidateBytes == '' then - return 'INVALID' - end -elseif expectedBytes == '' or candidateBytes == '' then - return 'INVALID' -end - -local currentBytes = redis.call('GET', KEYS[1]) -if currentBytes ~= false and redis.call('PTTL', KEYS[1]) ~= -1 then - return 'TTL_PRESENT' -end - -if mode == 'VERIFY' then - if currentBytes == expectedBytes then - return 'REPLAY' - end - return 'STALE' -end - -if currentBytes == candidateBytes then - return 'REPLAY' -end - -if mode == 'ABSENT' then - if currentBytes ~= false then - return 'STALE' - end - redis.call('SET', KEYS[1], candidateBytes) - return 'APPLIED' -end - -if currentBytes ~= expectedBytes then - return 'STALE' -end - -redis.call('SET', KEYS[1], candidateBytes) -return 'APPLIED' diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java deleted file mode 100644 index 187109e6be..0000000000 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java +++ /dev/null @@ -1,360 +0,0 @@ -package integration.net.firedevops.firemud.gamesession; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.lang.reflect.Field; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; -import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; -import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; -import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; -import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; -import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ApplyResult; -import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.Outcome; -import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.core.io.ClassPathResource; -import org.springframework.data.redis.connection.RedisStandaloneConfiguration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.script.RedisScript; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** Redis integration; Account readbacks are minted by the client over its mocked response seam. */ -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -class IssuerAuthorityProjectionRedisIntegrationTest { - private static final String NAMESPACE = "test"; - private static final String QUERY_ID = "11111111-1111-4111-8111-111111111111"; - private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; - private static final String COORD_PASSWORD = "issuer-projection-integration-secret"; - private static final ObjectMapper JSON = new ObjectMapper(); - private static final RedisScript CAS_SCRIPT = - RedisScript.of( - new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH), - String.class); - - @Container - static final GenericContainer redis = - new GenericContainer<>("redis:7.2-alpine") - .withExposedPorts(6379) - .withCommand( - "redis-server", - "--save", - "", - "--appendonly", - "no", - "--user", - "gamesession_coord_app", - "on", - ">" + COORD_PASSWORD, - "~session:game:auth:issuer-generation:v1:*", - "+get", - "+set", - "+pttl", - "+eval", - "+evalsha", - "+script|exists", - "+script|load"); - - private String issuerId; - private RedisIssuerAuthorityProjectionStore store; - private LettuceConnectionFactory adminConnectionFactory; - private StringRedisTemplate adminTemplate; - - @BeforeEach - void startOwnerStoreAndTestOnlyAdminReadback() { - issuerId = "https://accounts.example.test/issuer/" + UUID.randomUUID(); - store = - new RedisIssuerAuthorityProjectionStore( - NAMESPACE, - new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( - redis.getHost(), - redis.getMappedPort(6379), - "gamesession_coord_app", - COORD_PASSWORD), - new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( - "redis-cache.test.invalid", 6380)); - store.init(); - - adminConnectionFactory = - new LettuceConnectionFactory( - new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379))); - adminConnectionFactory.afterPropertiesSet(); - adminTemplate = new StringRedisTemplate(adminConnectionFactory); - adminTemplate.afterPropertiesSet(); - } - - @AfterEach - void closeConnections() { - if (store != null) { - store.close(); - } - if (adminConnectionFactory != null) { - adminConnectionFactory.destroy(); - } - } - - @Test - void authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSnapshots() - throws Exception { - IssuerGenerationAuthorityEvent first = event("1", "2", "3", 1); - SourceReadback current = readback("2", "3", "1", first, null); - - ApplyResult bootstrap = store.apply(current, "2026-10-02T11:00:00Z"); - assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); - ProjectionSnapshot firstSnapshot = bootstrap.snapshot().orElseThrow(); - assertThat(firstSnapshot.key()).isEqualTo(key()); - assertThat(parse(firstSnapshot.json()).path("lastAppliedSourceOutboxSequence").asText()) - .isEqualTo("1"); - assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(firstSnapshot.json()); - assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); - - IssuerGenerationAuthorityEvent second = event("2", "3", "4", 2); - SourceReadback selected = readback("3", "4", "2", second, second); - ApplyResult advanced = store.apply(selected, "2026-10-02T11:01:00Z"); - assertThat(advanced.outcome()).isEqualTo(Outcome.APPLIED); - String deterministicCandidate = advanced.snapshot().orElseThrow().json(); - assertThat(parse(deterministicCandidate).path("lastAppliedSourceOutboxSequence").asText()) - .isEqualTo("2"); - - ApplyResult exactDuplicate = store.apply(selected, "ignored-for-no-op"); - assertThat(exactDuplicate.outcome()).isEqualTo(Outcome.NO_OP); - assertThat(exactDuplicate.snapshot().orElseThrow().json()).isEqualTo(deterministicCandidate); - assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(deterministicCandidate); - assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); - } - - @Test - void authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEvidence() - throws Exception { - ApplyResult bootstrap = - store.apply(readback("1", "1", "0", null, null), "2026-10-02T10:59:00Z"); - - assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); - JsonNode projection = parse(bootstrap.snapshot().orElseThrow().json()); - assertThat(projection.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("0"); - assertThat(projection.has("sourceEventId")).isFalse(); - assertThat(projection.has("sourceEventDigest")).isFalse(); - assertThat(projection.path("appliedSourceEvidence").isEmpty()).isTrue(); - assertThat(adminTemplate.opsForValue().get(key())) - .isEqualTo(bootstrap.snapshot().orElseThrow().json()); - assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); - } - - @Test - void gapAndAuthenticatedOlderDuplicateHaveDistinctNoMutationOutcomes() throws Exception { - IssuerGenerationAuthorityEvent first = event("1", "2", "3", 3); - IssuerGenerationAuthorityEvent second = event("2", "3", "4", 4); - assertThat(store.apply(readback("2", "3", "1", first, null), "stable-1").outcome()) - .isEqualTo(Outcome.APPLIED); - assertThat(store.apply(readback("3", "4", "2", second, second), "stable-2").outcome()) - .isEqualTo(Outcome.APPLIED); - String before = adminTemplate.opsForValue().get(key()); - - IssuerGenerationAuthorityEvent fourth = event("4", "6", "7", 6); - ApplyResult gap = store.apply(readback("6", "7", "4", fourth, fourth), "ignored-for-gap"); - assertThat(gap.outcome()).isEqualTo(Outcome.QUARANTINED); - assertThat(gap.detail()).contains("EVENT_SEQUENCE_GAP"); - assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); - - ApplyResult olderDuplicate = - store.apply(readback("3", "4", "2", second, first), "ignored-for-older-duplicate"); - assertThat(olderDuplicate.outcome()).isEqualTo(Outcome.NO_OP); - assertThat(olderDuplicate.transitionDecision().orElseThrow()) - .isInstanceOf(IssuerAuthorityProjectionTransitions.NoOp.class); - assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); - assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); - } - - @Test - void staleExpectedBytesAreNonMutatingThroughTheRegisteredOwnerScript() { - String key = key(); - adminTemplate.opsForValue().set(key, "newer exact bytes"); - String result = executeRegistered(key, "PRESENT", "older exact bytes", "stale candidate bytes"); - - assertThat(result).isEqualTo("STALE"); - assertThat(adminTemplate.opsForValue().get(key())).isEqualTo("newer exact bytes"); - assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); - } - - @Test - void unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl() throws Exception { - String key = key(); - String unknownFieldJson = "{\"schemaVersion\":\"unknown\",\"extra\":true}"; - adminTemplate.opsForValue().set(key, unknownFieldJson); - IssuerGenerationAuthorityEvent event = event("2", "3", "4", 7); - - ApplyResult unknown = store.apply(readback("3", "4", "2", event, event), "stable-time"); - - assertThat(unknown.outcome()).isEqualTo(Outcome.QUARANTINED); - assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(unknownFieldJson); - assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); - - String duplicatePropertyJson = - "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"," - + "\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"}"; - adminTemplate.opsForValue().set(key, duplicatePropertyJson); - ApplyResult duplicateProperty = - store.apply(readback("3", "4", "2", event, event), "stable-time"); - assertThat(duplicateProperty.outcome()).isEqualTo(Outcome.QUARANTINED); - assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(duplicatePropertyJson); - assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); - } - - @Test - void expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration() throws Exception { - IssuerGenerationAuthorityEvent first = event("1", "2", "3", 8); - assertThat(store.apply(readback("2", "3", "1", first, null), "stable-time").outcome()) - .isEqualTo(Outcome.APPLIED); - String before = adminTemplate.opsForValue().get(key()); - adminTemplate.expire(key(), 30, TimeUnit.SECONDS); - Long beforeTtl = adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS); - - IssuerGenerationAuthorityEvent second = event("2", "3", "4", 9); - ApplyResult result = store.apply(readback("3", "4", "2", second, second), "stable-time"); - - assertThat(result.outcome()).isEqualTo(Outcome.QUARANTINED); - assertThat(result.detail()).contains("TTL_PRESENT"); - assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); - assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)) - .isPositive() - .isLessThanOrEqualTo(beforeTtl); - } - - private SourceReadback readback( - String generation, - String sourceVersion, - String sequence, - IssuerGenerationAuthorityEvent latest, - IssuerGenerationAuthorityEvent selected) - throws Exception { - String scope = "issuer/" + issuerId; - String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope; - IssuerAuthoritySourceSnapshot.Builder snapshot = - IssuerAuthoritySourceSnapshot.newBuilder() - .setIssuerId(issuerId) - .setSourceScope(scope) - .setOutboxStreamKey(streamKey) - .setIssuerAuthGeneration(generation) - .setSourceVersion(sourceVersion) - .setOutboxSequence(sequence); - if (latest != null) { - snapshot.setLatestEventCanonicalJson(latest.canonicalJson()); - } - ReadIssuerAuthorityForRuntimeResponse.Builder response = - ReadIssuerAuthorityForRuntimeResponse.newBuilder() - .setSchemaVersion("account-auth-issuer-source-readback/v1") - .setTargetNamespace(NAMESPACE) - .setRequestId(QUERY_ID) - .setSourceSnapshot(snapshot.build()); - if (selected != null) { - response.setRequestedEventCanonicalJson(selected.canonicalJson()); - } - - IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = - mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); - when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); - when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) - .thenReturn(response.build()); - AccountIssuerAuthorityClient client = newClient(stub); - if (selected == null) { - return client.readCurrent(QUERY_ID); - } - return client.readCommittedEvent(QUERY_ID, selected.outboxSequence()); - } - - private String executeRegistered( - String key, String expectedMode, String expectedBytes, String candidateBytes) { - var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); - var request = - new InvocationRequest( - descriptor.scriptId(), - descriptor.resourcePath(), - descriptor.sha256(), - descriptor.owner(), - descriptor.principal(), - descriptor.role(), - List.of(key), - List.of(expectedMode, expectedBytes, candidateBytes)); - var invocation = IssuerAuthorityProjectionRedisContract.registry().prepareInvocation(request); - assertThat(invocation.descriptor()).isSameAs(descriptor); - return adminTemplate.execute( - CAS_SCRIPT, List.of(key), expectedMode, expectedBytes, candidateBytes); - } - - private String key() { - return IssuerAuthorityProjectionRedisContract.keyForIssuer(issuerId); - } - - private static JsonNode parse(String json) throws Exception { - return JSON.readTree(json); - } - - private IssuerGenerationAuthorityEvent event( - String sequence, String generation, String sourceVersion, int identity) { - String requestId = String.format(Locale.ROOT, "00000000-0000-4000-8000-%012d", identity); - String scope = "issuer/" + issuerId; - return IssuerGenerationAuthorityEventV1Codec.seal( - Map.of( - "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, - "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, - "eventId", EVENT_ID_PREFIX + requestId, - "requestId", requestId, - "issuerId", issuerId, - "sourceScope", scope, - "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, - "outboxSequence", sequence, - "issuerAuthGeneration", generation, - "sourceVersion", sourceVersion)); - } - - private AccountIssuerAuthorityClient newClient( - IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub) throws Exception { - AccountIssuerAuthorityClient client = - new AccountIssuerAuthorityClient( - new ServiceEndpointsProperties(), - mtlsProperties(), - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - NAMESPACE, - issuerId); - Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - stubField.setAccessible(true); - stubField.set(client, stub); - return client; - } - - private static CommonGrpcClientProperties mtlsProperties() { - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setCertChain("certs/game-session-client.crt"); - tls.setPrivateKey("certs/game-session-client.key"); - tls.setCaCert("certs/account-ca.crt"); - return tls; - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java deleted file mode 100644 index 2718de39e4..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package unit.net.firedevops.firemud.gamesession.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; -import org.junit.jupiter.api.Test; - -class IssuerAuthorityProjectionRedisContractTest { - private static final String ISSUER_ID = "https://accounts.example.test/issuer"; - - @Test - void descriptorPinsOwnerPrincipalRoleResourceKeyAndArguments() { - var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); - - assertThat(descriptor.scriptId()).isEqualTo("game-session.issuer-authority-projection.v1"); - assertThat(descriptor.resourcePath()).isEqualTo("redis/issuer_authority_projection_cas.lua"); - assertThat(descriptor.owner()).isEqualTo("game-session-service"); - assertThat(descriptor.principal()).isEqualTo("gamesession_coord_app"); - assertThat(descriptor.role()).isEqualTo(RedisRole.COORDINATION); - assertThat(descriptor.resetSensitivity()).isEqualTo(ResetSensitivity.CLUSTER); - assertThat(descriptor.lossClass()).isEqualTo(LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP); - assertThat(descriptor.tailLossBehavior()) - .contains("quarantine this issuer scope") - .contains("never admit"); - assertThat(IssuerAuthorityProjectionRedisContract.PROJECTION_SCHEMA_VERSION) - .isEqualTo("game-session-auth-issuer-projection/v1"); - assertThat(descriptor.keys()) - .singleElement() - .satisfies( - key -> { - assertThat(key.ownedPrefix()).isEqualTo("session:game:auth:issuer-generation:v1:"); - assertThat(key.hashTagDeclaration()).isEqualTo(HashTagDeclaration.NOT_REQUIRED); - }); - assertThat(descriptor.arguments()) - .extracting(argument -> argument.name()) - .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); - assertThat(descriptor.outcomes()) - .extracting(outcome -> outcome.code()) - .containsExactly("APPLIED", "REPLAY", "STALE", "INVALID", "TTL_PRESENT"); - assertThat(IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID)) - .isEqualTo("session:game:auth:issuer-generation:v1:" + ISSUER_ID); - } - - @Test - void registryAcceptsOnlyTheRegisteredOwnerInvocation() { - var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); - String key = IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID); - InvocationRequest valid = - new InvocationRequest( - descriptor.scriptId(), - descriptor.resourcePath(), - descriptor.sha256(), - descriptor.owner(), - descriptor.principal(), - descriptor.role(), - List.of(key), - List.of("ABSENT", "", "{}")); - - assertThat(IssuerAuthorityProjectionRedisContract.registry().prepareInvocation(valid).keys()) - .containsExactly(key); - assertThatThrownBy( - () -> - IssuerAuthorityProjectionRedisContract.registry() - .prepareInvocation( - new InvocationRequest( - valid.scriptId(), - valid.resourcePath(), - valid.sha256(), - valid.owner(), - valid.principal(), - RedisRole.CACHE_RATE_LIMIT, - valid.keys(), - valid.arguments()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Redis role"); - assertThatThrownBy( - () -> - IssuerAuthorityProjectionRedisContract.registry() - .prepareInvocation( - new InvocationRequest( - valid.scriptId(), - "redis/unregistered.lua", - valid.sha256(), - valid.owner(), - valid.principal(), - valid.role(), - valid.keys(), - valid.arguments()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("script resource path"); - } - - @Test - void ownerKeyBuilderRejectsMissingOrControlCharacterIssuer() { - assertThatThrownBy(() -> IssuerAuthorityProjectionRedisContract.keyForIssuer(" ")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> IssuerAuthorityProjectionRedisContract.keyForIssuer("issuer\nother")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java deleted file mode 100644 index fef3948c4a..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java +++ /dev/null @@ -1,399 +0,0 @@ -package unit.net.firedevops.firemud.gamesession.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Field; -import java.math.BigInteger; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; -import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; -import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; -import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; -import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; -import org.junit.jupiter.api.Test; - -/** Decision/unit proof using AccountIssuerAuthorityClient's existing mocked response seam. */ -class IssuerAuthorityProjectionTransitionsTest { - private static final String ISSUER_ID = "https://accounts.example.test/issuer"; - private static final String NAMESPACE = "test"; - private static final String QUERY_ID = "11111111-1111-4111-8111-111111111111"; - private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; - - @Test - void bootstrapAtProvedSequenceZeroOmitsEventIdentityAndKeepsCallerAppliedAt() throws Exception { - SourceReadback readback = readback(ISSUER_ID, "1", "1", "0", null, null); - - IssuerAuthorityProjectionTransitions.Mutation mutation = - (IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.bootstrap(readback, "2026-10-02T11:00:00Z"); - - assertThat(mutation.kind()) - .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.BOOTSTRAP); - assertThat(mutation.expectedProjection()).isEmpty(); - assertThat(mutation.nextProjection()) - .containsEntry("schemaVersion", IssuerAuthorityProjectionTransitions.SCHEMA_VERSION) - .containsEntry("issuerId", ISSUER_ID) - .containsEntry("issuerAuthGeneration", "1") - .containsEntry("lastAppliedSourceOutboxSequence", "0") - .containsEntry("appliedAt", "2026-10-02T11:00:00Z") - .containsEntry("appliedSourceEvidence", Map.of()); - assertThat(mutation.nextProjection()).doesNotContainKeys("sourceEventId", "sourceEventDigest"); - } - - @Test - void bootstrapPositiveCurrentCheckpointRetainsCompleteLatestEventEvidence() throws Exception { - IssuerGenerationAuthorityEvent event = event("7", "92", "105", 1, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "92", "105", "7", event, null); - - IssuerAuthorityProjectionTransitions.Mutation mutation = - (IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); - - assertThat(mutation.nextProjection()) - .containsEntry("issuerAuthGeneration", "92") - .containsEntry("lastAppliedSourceOutboxSequence", "7") - .containsEntry("sourceEventId", event.eventId()) - .containsEntry("sourceEventDigest", event.eventDigest()) - .containsEntry("appliedSourceEvidence", Map.of("7", event.canonicalJson())); - assertThat(mutation.nextProjection()).doesNotContainKey("admitted"); - } - - @Test - void mutationCandidateAccessorReturnsDefensiveImmutableCopies() throws Exception { - IssuerGenerationAuthorityEvent event = event("1", "2", "3", 24, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "2", "3", "1", event, null); - IssuerAuthorityProjectionTransitions.Mutation mutation = - (IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); - - Map first = mutation.nextProjection(); - Map second = mutation.nextProjection(); - - assertThat(first).isEqualTo(second).isNotSameAs(second); - assertThatThrownBy(() -> first.put("unexpected", true)) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void bootstrapRejectsHistoricalSelectionWithoutProducingProjection() throws Exception { - IssuerGenerationAuthorityEvent latest = event("3", "4", "6", 2, ISSUER_ID); - IssuerGenerationAuthorityEvent selected = event("2", "3", "5", 1, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "4", "6", "3", latest, selected); - - IssuerAuthorityProjectionTransitions.Quarantine decision = - (IssuerAuthorityProjectionTransitions.Quarantine) - IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); - - assertThat(decision.reason()) - .isEqualTo( - IssuerAuthorityProjectionTransitions.QuarantineReason - .BOOTSTRAP_REQUIRES_CURRENT_READBACK); - assertThat(decision.expectedProjection()).isEmpty(); - } - - @Test - void selectedContiguousEventAdvancesWatermarkAndCheckpointEvenWhenGenerationIsEqual() - throws Exception { - IssuerGenerationAuthorityEvent prior = event("4", "80", "102", 4, ISSUER_ID); - Map existing = bootstrapProjection("80", "102", "4", prior); - IssuerGenerationAuthorityEvent next = event("5", "80", "103", 5, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "80", "103", "5", next, next); - - IssuerAuthorityProjectionTransitions.Mutation mutation = - (IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(mutation.kind()) - .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.ADVANCE); - assertThat(mutation.expectedProjection()).contains(existing); - assertThat(mutation.nextProjection()) - .containsEntry("issuerAuthGeneration", "80") - .containsEntry("lastAppliedSourceOutboxSequence", "5") - .containsEntry("sourceEventId", next.eventId()) - .containsEntry("sourceEventDigest", next.eventDigest()) - .containsEntry("appliedSourceEvidence", Map.of("5", next.canonicalJson())); - } - - @Test - void selectedContiguousEventUsesHigherGenerationWhenAccountAdvancedIt() throws Exception { - IssuerGenerationAuthorityEvent prior = event("4", "80", "102", 20, ISSUER_ID); - Map existing = bootstrapProjection("80", "102", "4", prior); - IssuerGenerationAuthorityEvent next = event("5", "81", "103", 21, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "81", "103", "5", next, next); - - IssuerAuthorityProjectionTransitions.Mutation mutation = - (IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(mutation.nextProjection()) - .containsEntry("issuerAuthGeneration", "81") - .containsEntry("lastAppliedSourceOutboxSequence", "5"); - } - - @Test - void sequenceGapQuarantinesWithoutReturningAMutationCandidate() throws Exception { - IssuerGenerationAuthorityEvent prior = event("1", "2", "3", 6, ISSUER_ID); - Map existing = bootstrapProjection("2", "3", "1", prior); - IssuerGenerationAuthorityEvent gap = event("3", "4", "5", 7, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "4", "5", "3", gap, gap); - - IssuerAuthorityProjectionTransitions.Quarantine decision = - (IssuerAuthorityProjectionTransitions.Quarantine) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(decision.reason()) - .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.EVENT_SEQUENCE_GAP); - assertThat(decision.expectedProjection()).contains(existing); - } - - @Test - void malformedExistingProjectionQuarantinesBeforeConsideringAccountEvent() throws Exception { - IssuerGenerationAuthorityEvent first = event("1", "2", "2", 22, ISSUER_ID); - Map validProjection = bootstrapProjection("2", "2", "1", first); - Map malformedProjection = new LinkedHashMap<>(validProjection); - malformedProjection.put("issuerAuthGeneration", "02"); - IssuerGenerationAuthorityEvent next = event("2", "2", "3", 23, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "2", "3", "2", next, next); - - IssuerAuthorityProjectionTransitions.Quarantine decision = - (IssuerAuthorityProjectionTransitions.Quarantine) - IssuerAuthorityProjectionTransitions.decide( - malformedProjection, readback, "stable-applied-at"); - - assertThat(decision.reason()) - .isEqualTo( - IssuerAuthorityProjectionTransitions.QuarantineReason.MALFORMED_EXISTING_PROJECTION); - assertThat(decision.expectedProjection()).contains(malformedProjection); - } - - @Test - void exactDuplicateIsNoOpAndDoesNotReplaceAppliedAt() throws Exception { - IssuerGenerationAuthorityEvent applied = event("2", "3", "4", 8, ISSUER_ID); - Map existing = bootstrapProjection("3", "4", "2", applied); - SourceReadback readback = readback(ISSUER_ID, "3", "4", "2", applied, applied); - - IssuerAuthorityProjectionTransitions.NoOp decision = - (IssuerAuthorityProjectionTransitions.NoOp) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "ignored-for-no-op"); - - assertThat(decision.reason()) - .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.EXACT_DUPLICATE); - assertThat(existing).containsEntry("appliedAt", "stable-time"); - } - - @Test - void duplicateWithDifferentCompleteCanonicalEventQuarantines() throws Exception { - IssuerGenerationAuthorityEvent applied = event("1", "2", "2", 9, ISSUER_ID); - Map existing = bootstrapProjection("2", "2", "1", applied); - IssuerGenerationAuthorityEvent conflicting = event("1", "2", "2", 10, ISSUER_ID); - IssuerGenerationAuthorityEvent current = event("2", "3", "3", 11, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "3", "3", "2", current, conflicting); - - IssuerAuthorityProjectionTransitions.Quarantine decision = - (IssuerAuthorityProjectionTransitions.Quarantine) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(decision.reason()) - .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.DUPLICATE_EVENT_CONFLICT); - assertThat(existing).containsEntry("lastAppliedSourceOutboxSequence", "1"); - } - - @Test - void authenticatedHistoricalDuplicateMayHaveLowerGenerationAndSourceVersion() throws Exception { - IssuerGenerationAuthorityEvent first = event("1", "2", "3", 12, ISSUER_ID); - IssuerGenerationAuthorityEvent later = event("2", "4", "6", 13, ISSUER_ID); - Map existing = bootstrapProjection("4", "6", "2", later); - SourceReadback readback = readback(ISSUER_ID, "4", "6", "2", later, first); - - IssuerAuthorityProjectionTransitions.NoOp decision = - (IssuerAuthorityProjectionTransitions.NoOp) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(decision.reason()) - .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.VERIFIED_HISTORICAL_DUPLICATE); - } - - @Test - void currentAccountCheckpointRegressionQuarantinesEvenForAContiguousSelectedEvent() - throws Exception { - IssuerGenerationAuthorityEvent installed = event("2", "8", "9", 14, ISSUER_ID); - Map existing = bootstrapProjection("8", "9", "2", installed); - IssuerGenerationAuthorityEvent regressedCurrent = event("3", "7", "8", 15, ISSUER_ID); - SourceReadback readback = - readback(ISSUER_ID, "7", "8", "3", regressedCurrent, regressedCurrent); - - IssuerAuthorityProjectionTransitions.Quarantine decision = - (IssuerAuthorityProjectionTransitions.Quarantine) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(decision.reason()) - .isEqualTo( - IssuerAuthorityProjectionTransitions.QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); - } - - @Test - void differentIssuerStreamProjectionQuarantines() throws Exception { - String otherIssuer = "https://other.example.test/issuer"; - IssuerGenerationAuthorityEvent otherEvent = event("1", "2", "3", 16, otherIssuer); - Map existing = bootstrapProjection(otherIssuer, "2", "3", "1", otherEvent); - IssuerGenerationAuthorityEvent current = event("1", "2", "3", 17, ISSUER_ID); - SourceReadback readback = readback(ISSUER_ID, "2", "3", "1", current, current); - - IssuerAuthorityProjectionTransitions.Quarantine decision = - (IssuerAuthorityProjectionTransitions.Quarantine) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(decision.reason()) - .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.ISSUER_OR_STREAM_CHANGED); - } - - @Test - void countersBeyondLongRemainExactAndNoSequenceGenerationEquationIsAssumed() throws Exception { - BigInteger sequence = new BigInteger("922337203685477580812345678901234567891"); - BigInteger priorSequence = sequence.subtract(BigInteger.ONE); - String generation = "800000000000000000000000000000000000001"; - BigInteger priorVersion = new BigInteger("800000000000000000000000000000000000010"); - String version = priorVersion.add(BigInteger.ONE).toString(); - IssuerGenerationAuthorityEvent prior = - event(priorSequence.toString(), generation, priorVersion.toString(), 18, ISSUER_ID); - Map existing = - bootstrapProjection(generation, priorVersion.toString(), priorSequence.toString(), prior); - IssuerGenerationAuthorityEvent next = - event(sequence.toString(), generation, version, 19, ISSUER_ID); - SourceReadback readback = - readback(ISSUER_ID, generation, version, sequence.toString(), next, next); - - IssuerAuthorityProjectionTransitions.Mutation mutation = - (IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); - - assertThat(mutation.nextProjection()) - .containsEntry("lastAppliedSourceOutboxSequence", sequence.toString()) - .containsEntry("issuerAuthGeneration", generation) - .containsEntry("sourceEventId", next.eventId()); - } - - private static Map bootstrapProjection( - String generation, - String sourceVersion, - String sequence, - IssuerGenerationAuthorityEvent latest) - throws Exception { - return bootstrapProjection(ISSUER_ID, generation, sourceVersion, sequence, latest); - } - - private static Map bootstrapProjection( - String issuerId, - String generation, - String sourceVersion, - String sequence, - IssuerGenerationAuthorityEvent latest) - throws Exception { - SourceReadback readback = readback(issuerId, generation, sourceVersion, sequence, latest, null); - return ((IssuerAuthorityProjectionTransitions.Mutation) - IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time")) - .nextProjection(); - } - - private static SourceReadback readback( - String issuerId, - String generation, - String sourceVersion, - String sequence, - IssuerGenerationAuthorityEvent latest, - IssuerGenerationAuthorityEvent selected) - throws Exception { - String sourceScope = "issuer/" + issuerId; - String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; - IssuerAuthoritySourceSnapshot.Builder snapshot = - IssuerAuthoritySourceSnapshot.newBuilder() - .setIssuerId(issuerId) - .setSourceScope(sourceScope) - .setOutboxStreamKey(streamKey) - .setIssuerAuthGeneration(generation) - .setSourceVersion(sourceVersion) - .setOutboxSequence(sequence); - if (latest != null) { - snapshot.setLatestEventCanonicalJson(latest.canonicalJson()); - } - ReadIssuerAuthorityForRuntimeResponse.Builder response = - ReadIssuerAuthorityForRuntimeResponse.newBuilder() - .setSchemaVersion("account-auth-issuer-source-readback/v1") - .setTargetNamespace(NAMESPACE) - .setRequestId(QUERY_ID) - .setSourceSnapshot(snapshot.build()); - if (selected != null) { - response.setRequestedEventCanonicalJson(selected.canonicalJson()); - } - - IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = - mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); - when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); - when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) - .thenReturn(response.build()); - AccountIssuerAuthorityClient client = newClient(stub, issuerId); - if (selected == null) { - return client.readCurrent(QUERY_ID); - } - return client.readCommittedEvent(QUERY_ID, selected.outboxSequence()); - } - - private static IssuerGenerationAuthorityEvent event( - String sequence, String generation, String sourceVersion, int identity, String issuerId) { - String requestId = String.format(Locale.ROOT, "00000000-0000-4000-8000-%012d", identity); - String scope = "issuer/" + issuerId; - return IssuerGenerationAuthorityEventV1Codec.seal( - Map.of( - "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, - "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, - "eventId", EVENT_ID_PREFIX + requestId, - "requestId", requestId, - "issuerId", issuerId, - "sourceScope", scope, - "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, - "outboxSequence", sequence, - "issuerAuthGeneration", generation, - "sourceVersion", sourceVersion)); - } - - private static AccountIssuerAuthorityClient newClient( - IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, String issuerId) - throws Exception { - AccountIssuerAuthorityClient client = - new AccountIssuerAuthorityClient( - new ServiceEndpointsProperties(), - mtlsProperties(), - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - NAMESPACE, - issuerId); - Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - stubField.setAccessible(true); - stubField.set(client, stub); - return client; - } - - private static CommonGrpcClientProperties mtlsProperties() { - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setCertChain("certs/game-session-client.crt"); - tls.setPrivateKey("certs/game-session-client.key"); - tls.setCaCert("certs/account-ca.crt"); - return tls; - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java deleted file mode 100644 index 452361d460..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package unit.net.firedevops.firemud.gamesession.service; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; -import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; -import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; -import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; -import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; -import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; -import org.junit.jupiter.api.Test; -import org.springframework.data.redis.core.RedisTemplate; - -class RedisIssuerAuthorityProjectionStoreTest { - private static final String COORD_PASSWORD = "coordination-secret"; - private static final String ISSUER_ID = "https://accounts.example.test/issuer"; - private static final String REQUEST_ID = "11111111-1111-4111-8111-111111111111"; - - @Test - void requiresExactCoordinationPrincipalAndCredentials() { - assertThatThrownBy( - () -> - new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( - "coordination.internal", 6379, "gamesession_cache_app", COORD_PASSWORD)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("gamesession_coord_app"); - assertThatThrownBy( - () -> - new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( - "coordination.internal", 6379, "gamesession_coord_app", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("credential"); - } - - @Test - void rejectsNormalizedCoordinationAndCacheEndpointCollision() { - var coordination = - new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( - "redis-coord.internal.", 6379, "gamesession_coord_app", COORD_PASSWORD); - var cache = - new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( - "REDIS-COORD.INTERNAL", 6379); - - assertThatThrownBy(() -> new RedisIssuerAuthorityProjectionStore("test", coordination, cache)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("endpoints must be distinct"); - } - - @Test - void constructorRequiresBothTypedRoleEndpointsWithoutOpeningRedis() { - var store = - new RedisIssuerAuthorityProjectionStore( - "test", - coordination("coordination.internal", 6379), - new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("cache.internal", 6379)); - - assertThatThrownBy(() -> store.apply(null, "stable-time")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("explicit init()"); - store.close(); - } - - @Test - void wrongSourceNamespaceIsRejectedBeforeAnyRedisCommand() throws Exception { - RedisIssuerAuthorityProjectionStore store = - new RedisIssuerAuthorityProjectionStore( - "other", - coordination("127.0.0.1", 1), - new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("127.0.0.1", 2)); - store.init(); - - try { - var result = store.apply(sourceReadback("test"), "stable-time"); - - assertThat(result.outcome()) - .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); - assertThat(result.detail()).contains("ACCOUNT_NAMESPACE_MISMATCH"); - } finally { - store.close(); - } - } - - @Test - void coordinationCredentialIsRedactedAndNoAmbientRedisTemplateConstructorExists() - throws Exception { - var endpoint = coordination("coordination.internal", 6379); - - assertThat(endpoint.toString()).contains("password=").doesNotContain(COORD_PASSWORD); - boolean acceptsAmbientTemplate = - Arrays.stream(RedisIssuerAuthorityProjectionStore.class.getConstructors()) - .anyMatch( - constructor -> - Arrays.stream(constructor.getParameterTypes()) - .anyMatch(RedisTemplate.class::isAssignableFrom)); - assertThat(acceptsAmbientTemplate).isFalse(); - } - - private static RedisIssuerAuthorityProjectionStore.CoordinationEndpoint coordination( - String host, int port) { - return new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( - host, port, "gamesession_coord_app", COORD_PASSWORD); - } - - private static SourceReadback sourceReadback(String targetNamespace) throws Exception { - String scope = "issuer/" + ISSUER_ID; - IssuerAuthoritySourceSnapshot snapshot = - IssuerAuthoritySourceSnapshot.newBuilder() - .setIssuerId(ISSUER_ID) - .setSourceScope(scope) - .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) - .setIssuerAuthGeneration("1") - .setSourceVersion("1") - .setOutboxSequence("0") - .build(); - ReadIssuerAuthorityForRuntimeResponse response = - ReadIssuerAuthorityForRuntimeResponse.newBuilder() - .setSchemaVersion("account-auth-issuer-source-readback/v1") - .setTargetNamespace(targetNamespace) - .setRequestId(REQUEST_ID) - .setSourceSnapshot(snapshot) - .build(); - IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = - mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); - when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); - when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) - .thenReturn(response); - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setCertChain("certs/game-session-client.crt"); - tls.setPrivateKey("certs/game-session-client.key"); - tls.setCaCert("certs/account-ca.crt"); - AccountIssuerAuthorityClient client = - new AccountIssuerAuthorityClient( - new ServiceEndpointsProperties(), - tls, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - "test", - ISSUER_ID); - Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - stubField.setAccessible(true); - stubField.set(client, stub); - return client.readCurrent(REQUEST_ID); - } -} diff --git a/settings.gradle.kts b/settings.gradle.kts index 65b4497aa6..4894fe1e4e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -7,9 +7,6 @@ rootProject.name = "firemud" include("common-data-runtime") project(":common-data-runtime").projectDir = File("services/common-data-runtime") -include("common-redis-contracts") -project(":common-redis-contracts").projectDir = File("services/common-redis-contracts") - include("common-platform-core") project(":common-platform-core").projectDir = File("services/common-platform-core") From f9f51475c49acf0d4cb4b09443c729c7558bdab6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:36:20 +1300 Subject: [PATCH 16/22] Record source proof and child handoff after coherent boundary split --- .../implementation-tracking/player-access-and-session.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5de411d244..1377cd627a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The active [#2933](https://github.com/benhook1013/FireMUD/pull/2933) boundary retains Account password-reset and issuer source authority, exact retained-tenant UUID handoff, Game Logic UUID preservation and authenticated current/historical source transport proof. Its coherent Redis foundation/derived projection has moved to the existing [#2938](https://github.com/benhook1013/FireMUD/pull/2938) Account source child; the cumulative child tree is preserved exactly through normal history. This regrouping reduces the parent scope from100 to77paths without dropping source implementation or proof. + +Exact preceding checkpoint933d1f035 [CI36970584573](https://github.com/benhook1013/FireMUD/actions/runs/36970584573) passed Game Session/TCP. All16 WebSocket PostgreSQL cases executed cleanly, including the signed-context fail-closed case; this suite is strict-log evidence, not uploaded raw XML. Seven component XML suites prove62 clean cases without skips/failures/errors. Aggregate CI is still red on separately owned tooling/Automation/Game Design failures. The reduced parent full Game Session check/JAR and docs passed1m23s,131tasks(30executed/4from-cache/97up-to-date), with Docker-dependent cases skipped locally. Fresh regrouped-head CI and all complete recipient, deployment and runtime activation proof remain gates. Membership RPC and credential/context/catalog activation remain denied; the Account ring mount is unpublished. + +### Earlier component checkpoints + The issuer-source PostgreSQL-through-socket-mTLS cases remain focused source-handoff proof, not deployment or runtime activation. The derived issuer projection and owner-local Redis foundation, including their component proof, are assigned to [#2938](https://github.com/benhook1013/FireMUD/pull/2938). The projection grants no recipient, admission or rebind authority; exact recipient evidence remains required, and event delivery, role/ACL deployment, activation and active-binding revocation remain open. Exact published [CI 36959528382](https://github.com/benhook1013/FireMUD/actions/runs/36959528382) at `58695d165a03f6004236a8a5e27b1a99f1b0eae4` completed with aggregate failure. Raw XML proved all fifteen issuer PostgreSQL, seventeen retained-association and four snapshot cases executed without skips, failures or errors, along with six reset-producer and both required reset-application methods. Five of six socket mTLS cases passed; the missing-client-certificate assertion lost its underlying throwable, so its cause cannot be established from that result. The corrected test observes the certificate rejection directly with explicit trust-only credentials, bounded timeouts, HTTP/2 negotiation and diagnostics. LOGIN/PLAY/LOOK passed; all four remaining TCP chat-output failures were the Game Logic numeric Account validator rejecting the canonical UUID. The local correction preserves exact UUIDs through Game Logic, but Social's numeric sender store still needs its owner migration; a Social stub does not prove persistence or end-to-end delivery. From a80cd56f4488f97d9e8b7f4c70f2814503d54edf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:47:35 +1300 Subject: [PATCH 17/22] Converge canonical realm scope consumers and composed migration proof --- .github/workflows/ci.yml | 14 ++ .../game-session-service/api-contracts.md | 4 +- .../player-access-and-session.md | 4 +- .../service/impl/AccountServiceImplTest.java | 8 + ...untRuntimeStubServerCompatibilityTest.java | 24 ++- .../test/AccountRuntimeStubServerTest.java | 9 +- .../repository/VersionRepository.java | 23 ++- ...igestBaselineMigrationIntegrationTest.java | 8 +- .../repository/VersionRepositoryTest.java | 29 +++ .../command/text/PlayCommandHandler.java | 5 +- .../command/text/WorldsCommandHandler.java | 97 ++++++++-- .../DirectTextConnectScopeSessionStore.java | 31 ++- ...irectTextConnectScopeSessionStoreTest.java | 34 +++- ...essionWebSocketHandlerIntegrationTest.java | 4 +- .../command/text/PlayCommandHandlerTest.java | 37 ++-- .../text/SessionResumptionFlowTest.java | 5 +- .../text/TextCommandInterpreterTest.java | 5 +- .../text/WorldsCommandHandlerTest.java | 182 ++++++++++++++---- .../WorldsTextCommandDispatchHandlerTest.java | 68 +++++-- ...irectTextConnectScopeSessionStoreTest.java | 55 +++++- 20 files changed, 493 insertions(+), 153 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df93faab6d..54f6b18266 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -946,17 +946,31 @@ jobs: run: | ./gradlew :game-design-service:integrationTest \ --tests integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#appliesAuditedAssociationForFreshAndRetainedGameSources()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#versionLockRepositoryUsesConfiguredIsolatedOwnerSchema()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnOneImmutableReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#ownerRollbackLeavesNoClaimAndLostAcknowledgementRetryReadsExactReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges()' \ game-design-service + - name: Retain Game Design owner migration raw PostgreSQL evidence + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-owner-migration-proof-${{ github.sha }} + path: | + services/game-design-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest.xml + services/game-design-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest.xml + if-no-files-found: error + - name: Run Game Session authored-world intake PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 944cc8d67d..52e8de1e2e 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -14,6 +14,8 @@ Realm-catalog identity status: Game Session pointer and audit rows persist a sep This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: +The REALMS/JOIN consumer candidate carries the canonical tenant UUID from the exact namespace-qualified owner association in Account contexts and scope targets. Its lobby record retains the private Game Session catalog key separately as local routing metadata; JOIN rechecks that key's association against the stored UUID before forwarding. Missing, nil or changed association evidence denies without Account forwarding. This consumer is not the complete Account direct-text scope/JOIN producer, whose canonical caller/tenant and catalog-authority convergence remains open in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). Mocked consumer success does not prove enabled end-to-end JOIN, and activation gates remain closed. + The dedicated `AccountIssuerAuthorityClient` is an unwired source-only consumer candidate for [Account's issuer readback](../account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). It requires file-backed mutual TLS and the exact Account server workload identity, validates current and explicitly selected historical evidence with the shared issuer-event codec, and compares canonical decimal counters without narrowing them. Its transport result is not a recipient membership snapshot, admission or rebind authorization, an installed issuer projection, or a delivered revocation. Runtime activation remains denied until the complete producer, mutual peer authentication, projection and negative proof passes; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records executed and unavailable proof. - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; @@ -158,7 +160,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. -**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` returns `JOIN_REQUIRED` only for a complete, fresh `MISSING` or `INACTIVE` membership snapshot on an eligible public-production target after public joining is allowed. A complete `ACTIVE` snapshot with `gameplayAdmissionAllowed=false` returns `WORLD_ACCESS_DENIED` without binding. Unavailable or malformed authority remains unavailable. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. - **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert requires `0/0` as its expected-absent precondition; because no row exists to version-check, insert-race safety comes from runtime-target locking and database uniqueness constraints, not a row-version CAS. Neither condition is proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). 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 4220a5b66f..4422da1a0b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The active [#2933](https://github.com/benhook1013/FireMUD/pull/2933) boundary retains Account password-reset and issuer source authority, exact retained-tenant UUID handoff, Game Logic UUID preservation and authenticated current/historical source transport proof. Its coherent Redis foundation/derived projection has moved to the existing [#2938](https://github.com/benhook1013/FireMUD/pull/2938) Account source child; the cumulative child tree is preserved exactly through normal history. This regrouping reduces the parent scope from100 to77paths without dropping source implementation or proof. +The active [#2933](https://github.com/benhook1013/FireMUD/pull/2933) boundary retains Account password-reset and issuer source authority, exact retained-tenant UUID handoff, Game Logic UUID preservation and authenticated current/historical source transport proof. Its coherent Redis foundation/derived projection has moved to the existing [#2938](https://github.com/benhook1013/FireMUD/pull/2938) Account source child; the cumulative child tree is preserved exactly through normal history. That earlier regrouping reduced the parent scope from100 to77paths without dropping source implementation or proof; current reconciliation scope and exact-head proof are recorded on the owning PR. + +The reconciled REALMS/JOIN consumer candidate resolves only the exact namespace-qualified Game Session catalog-key association, sends its canonical tenant UUID unchanged in Account context and target, and stores the private catalog key separately. JOIN compares fresh association readback to the stored UUID before forwarding; absent, nil or changed evidence denies. Local mocked tests are component proof only. The Account direct-text scope/JOIN producer still parses private numeric caller/tenant fields and its runtime catalog reads do not yet prove canonical cross-owner tenant association. Canonical Account caller resolution, Account-owned tenant mapping, exact authenticated catalog evidence, durable scope/JOIN binding and composed positive/negative execution remain required before end-to-end availability. Do not forward a Game Session private key as an Account key, infer equality, or treat the consumer fixture as activation proof. Membership, credential/context/catalog/admission and ring gates remain unchanged. Exact preceding checkpoint933d1f035 [CI36970584573](https://github.com/benhook1013/FireMUD/actions/runs/36970584573) passed Game Session/TCP. All16 WebSocket PostgreSQL cases executed cleanly, including the signed-context fail-closed case; this suite is strict-log evidence, not uploaded raw XML. Seven component XML suites prove62 clean cases without skips/failures/errors. Aggregate CI is still red on separately owned tooling/Automation/Game Design failures. The reduced parent full Game Session check/JAR and docs passed1m23s,131tasks(30executed/4from-cache/97up-to-date), with Docker-dependent cases skipped locally. Fresh regrouped-head CI and all complete recipient, deployment and runtime activation proof remain gates. Membership RPC and credential/context/catalog activation remain denied; the Account ring mount is unpublished. 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 92b8232b63..f91b331098 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 @@ -4925,6 +4925,14 @@ void issueConnectTokenDoesNotReplayCachedLegacySuccess() { account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index d0a9fe5995..575d485f93 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -19,6 +19,7 @@ class AccountRuntimeStubServerCompatibilityTest { private static final String ACCOUNT_UUID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; private static final String OTHER_ACCOUNT_UUID = "c7dc8122-91d6-48c4-9484-9350c25d9b61"; + private static final String TENANT_UUID = "784e0d9c-714f-4a22-9404-04b8b37c8ef1"; private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; private static final String NAMESPACE_ID = "2ea958e0-13a2-41d0-9c39-59a96cf31412"; private static final Set NON_RUNTIME_METHODS = @@ -77,16 +78,22 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe server.denyGameplayAdmission(); var existingButNonAdmitting = - stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, "11")); + stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, TENANT_UUID)); assertThat(existingButNonAdmitting.getMembershipExists()).isTrue(); assertThat(existingButNonAdmitting.getGameplayAdmissionAllowed()).isFalse(); assertThat(existingButNonAdmitting.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(existingButNonAdmitting.getAuthorityAvailability()).isEqualTo("AVAILABLE"); assertThat(existingButNonAdmitting.getMembershipAuthorityGeneration()).isEqualTo("1"); assertThat(existingButNonAdmitting.getMembershipVersionMap()) .containsEntry(existingButNonAdmitting.getTenantId(), "1"); + assertThat(existingButNonAdmitting.getRolesList()).containsExactly("player"); + assertThat(existingButNonAdmitting.hasMembershipBaseline()).isTrue(); + assertThat(existingButNonAdmitting.hasAuthorityTuple()).isTrue(); + assertThat(existingButNonAdmitting.getOutboxSourceEvidenceCount()).isEqualTo(1); server.setMembershipExists(false); - var missing = stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, "11")); + var missing = + stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, TENANT_UUID)); assertThat(missing.getMembershipExists()).isFalse(); assertThat(missing.getGameplayAdmissionAllowed()).isFalse(); assertThat(missing.getMembershipLifecycleState()).isEqualTo("MISSING"); @@ -100,7 +107,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setTenantId("11") + .setTenantId(TENANT_UUID) .setRealmId(REALM_ID) .setGameInstanceId("33") .setSessionId("session-1") @@ -112,7 +119,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe stub.issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId("11") + .setTenantId(TENANT_UUID) .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) @@ -133,7 +140,8 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe .build()); assertThat(join.getSuccess()).isTrue(); - var afterJoin = stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, "11")); + var afterJoin = + stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, TENANT_UUID)); assertThat(afterJoin.getMembershipExists()).isTrue(); assertThat(afterJoin.getGameplayAdmissionAllowed()).isTrue(); assertThat(afterJoin.getMembershipLifecycleState()).isEqualTo("ACTIVE"); @@ -143,7 +151,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe stub.getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest.newBuilder() .setAccountId(ACCOUNT_UUID) - .setTenantId("11") + .setTenantId(TENANT_UUID) .setWorldSlug("demo") .setRealmSlug("live") .build()); @@ -282,7 +290,7 @@ private static IssueDirectTextConnectScopeRequest validConnectScopeRequest() { PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setTenantId("11") + .setTenantId(TENANT_UUID) .setRealmId(REALM_ID) .setGameInstanceId("33") .setSessionId("session-1") @@ -292,7 +300,7 @@ private static IssueDirectTextConnectScopeRequest validConnectScopeRequest() { .build(); return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId("11") + .setTenantId(TENANT_UUID) .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index cf03bd3b45..27c2b9de93 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -218,7 +218,7 @@ void rejectsNonCanonicalRuntimeTenantIdsWithoutReturningMembershipEvidence() thr } @Test - void contradictoryMembershipLifecycleAndAdmissionRemainDenied() throws Exception { + void activeMembershipCanBeDeniedWhileInactiveMembershipCannotBeAdmitted() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); @@ -229,9 +229,10 @@ void contradictoryMembershipLifecycleAndAdmissionRemainDenied() throws Exception server.setGameplayAdmissionAllowed(false); var activeButDenied = stub.getTenantMembershipForRuntime(membershipRequest(TENANT_UUID, "contradictory-1")); - assertContradictoryMembershipDenied(activeButDenied, "ACTIVE", "contradictory-1"); + assertMembershipEventMatches(activeButDenied, "ACTIVE", false, "contradictory-1"); server.denyGameplayAdmission(); + server.setMembershipInactive(); server.setGameplayAdmissionAllowed(true); var inactiveButAllowed = stub.getTenantMembershipForRuntime(membershipRequest(TENANT_UUID, "contradictory-2")); @@ -306,7 +307,7 @@ private static void assertMembershipEventMatches( "membershipAuthorityGeneration", Map.of(TENANT_UUID, "1"), "privateRealmGrantVersions", List.of())), Map.entry("issuanceFence", "1"), - Map.entry("roles", admitted ? List.of("player") : List.of()), + Map.entry("roles", lifecycle.equals("ACTIVE") ? List.of("player") : List.of()), Map.entry("gameplayAdmissionAllowed", admitted), Map.entry("callerBoundAuthorityInvalidated", false))); @@ -382,7 +383,7 @@ private static void assertMembershipSnapshotMatches( assertThat(response.getAuthorityTuple().hasTenantBillingCutoff()).isFalse(); assertThat(response.getIssuanceFence()).isEqualTo("1"); assertThat(response.getRolesList()) - .containsExactlyElementsOf(admitted ? List.of("player") : List.of()); + .containsExactlyElementsOf(lifecycle.equals("ACTIVE") ? List.of("player") : List.of()); assertThat(response.getOutboxCheckpointsList()) .containsExactly( checkpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID, "0"), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index 75fcc6bbf5..774bb6fa9a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -45,17 +45,11 @@ public class VersionRepository { DSL.field(DSL.name("updated_at"), Timestamp.class); private final DSLContext dsl; - private final String entityDigestBaselineMigrationVersionLockFunction; + private final String postgresSchema; public VersionRepository(DSLContext dsl, PostgresProperties postgres) { - this.dsl = Objects.requireNonNull(dsl); - String schema = Objects.requireNonNull(postgres).getSchema(); - if (schema == null || schema.isBlank()) { - throw new IllegalArgumentException("Game Design PostgreSQL schema must be configured"); - } - this.entityDigestBaselineMigrationVersionLockFunction = - dsl.render( - DSL.quotedName(schema, ENTITY_DIGEST_BASELINE_MIGRATION_VERSION_LOCK_FUNCTION_NAME)); + this.dsl = dsl; + this.postgresSchema = postgres == null ? null : postgres.getSchema(); } public List findAllByTenantIdOrderByVersionNumberAsc(String tenantId) { @@ -106,12 +100,21 @@ public Optional findByTenantIdAndIdForUpdate(String tenantId, Long id) */ public Optional findByTenantIdAndIdForEntityDigestBaselineMigration( String tenantId, Long id) { + if (postgresSchema == null || postgresSchema.isBlank()) { + throw new IllegalStateException( + "Game Design PostgreSQL schema must be configured for the " + + "Entity digest baseline Version lock"); + } + String versionLockFunction = + dsl.render( + DSL.quotedName( + postgresSchema, ENTITY_DIGEST_BASELINE_MIGRATION_VERSION_LOCK_FUNCTION_NAME)); return Optional.ofNullable( dsl.resultQuery( "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + "script_patch_version, base_version_id, is_script_only, notes, " + "created_at, updated_at FROM " - + entityDigestBaselineMigrationVersionLockFunction + + versionLockFunction + "(?, ?)", tenantId, id) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index d9a294db90..72c252962e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -369,10 +369,10 @@ void migrationDigestOverlapWithLifecycleTransitionRejectsStaleEpoch() throws Exc @Test void exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain() { - createGame("9301"); - Version version = createVersion("9301", 1); - RecordedParticipantDigest source = seedEntityBaseline("9301", version, 1); - MigrationCommand command = command("retry-operation", "9301", source); + createGame("9302"); + Version version = createVersion("9302", 1); + RecordedParticipantDigest source = seedEntityBaseline("9302", version, 1); + MigrationCommand command = command("retry-operation", "9302", source); MigrationResult first = migrationService.migrate(command); MigrationResult retry = migrationService.migrate(command); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java index f97dc8d95e..d4ea5b74de 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.gamedesign.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.sql.DriverManager; import java.time.LocalDateTime; import java.util.List; import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.gamedesign.entity.Version; @@ -41,6 +43,33 @@ void entityDigestBaselineVersionLockUsesConfiguredOwnerSchema() { "\"isolated_game_design_owner\".\"lock_version_for_entity_digest_baseline_migration\""); } + @Test + void entityDigestBaselineVersionLockRejectsMissingOrBlankOwnerSchemaWithoutQuery() { + AtomicInteger queryCount = new AtomicInteger(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + queryCount.incrementAndGet(); + return new MockResult[] {new MockResult(0, resultDsl.newResult())}; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + + for (String schema : new String[] {null, " "}) { + PostgresProperties postgres = new PostgresProperties(); + postgres.setSchema(schema); + VersionRepository repository = new VersionRepository(dsl, postgres); + + assertThatThrownBy( + () -> repository.findByTenantIdAndIdForEntityDigestBaselineMigration("tenant", 17L)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Game Design PostgreSQL schema must be configured for the " + + "Entity digest baseline Version lock"); + } + + assertThat(queryCount.get()).isZero(); + } + @Test void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible() throws Exception { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 36fb619ba8..947f49d618 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1042,7 +1042,6 @@ private boolean isValidMembershipLifecycleEvidence( && response.getRolesCount() == 0; case "ACTIVE" -> response.getMembershipExists() - && response.getGameplayAdmissionAllowed() && response.getRolesList().contains("player") && hasPositiveMembershipVersion(response); case "INACTIVE" -> @@ -1161,8 +1160,8 @@ private static boolean hasCompleteMembershipAuthorityCarrier( if (response.getOutboxSourceEvidenceCount() != 1 || !response.getMembershipExists() - || (response.getGameplayAdmissionAllowed() - != "ACTIVE".equals(response.getMembershipLifecycleState())) + || ("INACTIVE".equals(response.getMembershipLifecycleState()) + && response.getGameplayAdmissionAllowed()) || response.getMembershipVersionCount() != 1 || !hasPositiveMembershipVersion(response)) { return false; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index e65ca65bf2..545cd50d7d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -16,7 +16,9 @@ import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.springframework.beans.factory.annotation.Autowired; @@ -33,26 +35,38 @@ public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; private final AccountClient accountClient; private final DirectTextConnectScopeSessionStore connectScopeSessionStore; + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver; private final Clock clock; @Autowired public WorldsCommandHandler( GameplayWorldCatalog worldCatalog, AccountClient accountClient, - DirectTextConnectScopeSessionStore connectScopeSessionStore) { - this(worldCatalog, accountClient, connectScopeSessionStore, Clock.systemUTC()); + DirectTextConnectScopeSessionStore connectScopeSessionStore, + RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver) { + this( + worldCatalog, + accountClient, + connectScopeSessionStore, + retainedRuntimeTenantUuidResolver, + Clock.systemUTC()); } WorldsCommandHandler( GameplayWorldCatalog worldCatalog, AccountClient accountClient, DirectTextConnectScopeSessionStore connectScopeSessionStore, + RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver, Clock clock) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); this.connectScopeSessionStore = Objects.requireNonNull( connectScopeSessionStore, "connectScopeSessionStore must not be null"); + this.retainedRuntimeTenantUuidResolver = + Objects.requireNonNull( + retainedRuntimeTenantUuidResolver, + "retainedRuntimeTenantUuidResolver must not be null"); this.clock = Objects.requireNonNull(clock, "clock must not be null"); } @@ -148,11 +162,17 @@ public RealmBrowseResult browseRealms( if (accountClient == null) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); } - DirectTextConnectScopeTarget target = connectScopeTarget(world, realm); + Optional canonicalTenantId = canonicalTenantId(realm.tenantId()); + if (canonicalTenantId.isEmpty()) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + DirectTextConnectScopeTarget target = + connectScopeTarget(world, realm, canonicalTenantId.orElseThrow()); if (target == null) { return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - PlayerExecutionContext playerContext = playerContext(sessionContext, realm, requestId); + PlayerExecutionContext playerContext = + playerContext(sessionContext, realm, requestId, canonicalTenantId.orElseThrow()); IssueDirectTextConnectScopeResponse scopeResponse = accountClient.issueDirectTextConnectScope(playerContext, target); if (scopeResponse.hasError()) { @@ -176,7 +196,13 @@ public RealmBrowseResult browseRealms( } issuedScopes.add( new DirectTextConnectScopeSessionStore.ScopedRealm( - realm.slug(), true, scopeResponse.getConnectScopeId(), expiresAt, playerContext)); + realm.slug(), + realm.tenantId(), + true, + scopeResponse.getConnectScopeId(), + expiresAt, + playerContext, + "")); visibleEntries.add(realmEntry(visibleEntries.size() + 1, realm)); responseRealms.add(realm); } @@ -553,6 +579,32 @@ public JoinMembershipResult joinPublicProductionMembership( .equals(revalidatedRealmCatalog.orElseThrow().catalogFingerprint())) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } + long catalogTenantId = DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world); + Optional maybeStoredScope; + try { + maybeStoredScope = + connectScopeSessionStore.publicProductionScope( + sessionContext, catalogTenantId, world.slug(), clock.instant()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + if (maybeStoredScope.isEmpty()) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + DirectTextConnectScopeSessionStore.ScopedRealm storedScope = maybeStoredScope.orElseThrow(); + Optional currentCanonicalTenantId = canonicalTenantId(storedScope.localTenantId()); + if (currentCanonicalTenantId.isEmpty()) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + if (storedScope.localTenantId() != catalogTenantId + || !currentCanonicalTenantId + .orElseThrow() + .toString() + .equals(storedScope.playerContext().getTenantId())) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + Optional maybeJoinScope; try { maybeJoinScope = @@ -571,18 +623,20 @@ public JoinMembershipResult joinPublicProductionMembership( } DirectTextConnectScopeSessionStore.JoinScope joinScope = maybeJoinScope.orElseThrow(); DirectTextConnectScopeSessionStore.ScopedRealm scope = joinScope.scope(); - long tenantId; - try { - tenantId = Long.parseLong(scope.playerContext().getTenantId()); - } catch (NumberFormatException ex) { - return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + Optional revalidatedCanonicalTenantId = canonicalTenantId(scope.localTenantId()); + if (revalidatedCanonicalTenantId.isEmpty()) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } - if (tenantId != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { + if (scope.localTenantId() != catalogTenantId + || !revalidatedCanonicalTenantId + .orElseThrow() + .toString() + .equals(scope.playerContext().getTenantId())) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } boolean hasPublicProductionRealm; try { - hasPublicProductionRealm = worldCatalog.hasValidPublicProductionRealm(tenantId); + hasPublicProductionRealm = worldCatalog.hasValidPublicProductionRealm(catalogTenantId); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { @@ -604,7 +658,9 @@ private static String normalizeSelector(String selector) { } private DirectTextConnectScopeTarget connectScopeTarget( - GameplayWorldCatalog.WorldView world, GameplayWorldCatalog.RealmView realm) { + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmView realm, + UUID canonicalTenantId) { if (realm.tenantId() <= 0 || realm.gameInstanceId() <= 0 || realm.realmId() == null @@ -615,7 +671,7 @@ private DirectTextConnectScopeTarget connectScopeTarget( return null; } return new DirectTextConnectScopeTarget( - Long.toString(realm.tenantId()), + canonicalTenantId.toString(), world.slug(), realm.slug(), realm.realmId().toString(), @@ -627,11 +683,14 @@ private DirectTextConnectScopeTarget connectScopeTarget( } private PlayerExecutionContext playerContext( - SessionContext caller, GameplayWorldCatalog.RealmView realm, String requestId) { + SessionContext caller, + GameplayWorldCatalog.RealmView realm, + String requestId, + UUID canonicalTenantId) { return PlayerExecutionContext.newBuilder() .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) - .setTenantId(Long.toString(realm.tenantId())) + .setTenantId(canonicalTenantId.toString()) .setRealmId(realm.realmId().toString()) .setPlayableStateNamespaceId(realm.playableStateNamespaceId().toString()) .setPlayableStateScope(realm.stateScope()) @@ -640,6 +699,12 @@ private PlayerExecutionContext playerContext( .build(); } + private Optional canonicalTenantId(long localTenantId) { + return retainedRuntimeTenantUuidResolver + .resolveCanonicalTenantId(localTenantId) + .filter(tenantId -> AccountIds.isCanonicalNonNilUuid(tenantId.toString())); + } + private RealmBrowseViewOutput.RealmEntry realmEntry( int ordinal, GameplayWorldCatalog.RealmView realm) { return new RealmBrowseViewOutput.RealmEntry( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index 1cea65d656..04e2baf092 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -634,6 +634,7 @@ private StoredScopedRealm storeScope(ScopedRealm scope, long nowMillis) { String contextBase64 = Base64.getEncoder().encodeToString(scope.playerContext().toByteArray()); return new StoredScopedRealm( scope.realmSlug(), + scope.localTenantId(), scope.publicProductionRealm(), scope.connectScopeId(), boundedExpiry, @@ -648,6 +649,7 @@ private static ScopedRealm fromStoredScope(StoredScopedRealm stored) { Base64.getDecoder().decode(stored.playerContextBase64())); return new ScopedRealm( stored.realmSlug(), + stored.localTenantId(), stored.publicProductionRealm(), stored.connectScopeId(), Instant.ofEpochMilli(stored.expiresAtEpochMs()), @@ -666,24 +668,16 @@ private static void validateScopeIdentity( || !caller.accountId().equals(context.getAccountId()) || !Long.toString(caller.sessionId()).equals(context.getSessionId()) || tenantId <= 0L - || !Long.toString(tenantId).equals(context.getTenantId())) { + || scope.localTenantId() != tenantId + || !AccountIds.isCanonicalNonNilUuid(context.getTenantId())) { throw new ConflictingIdentityException("Account scope caller identity did not match session"); } } - private static long parsePositiveLong(String value) { - try { - long parsed = Long.parseLong(value); - return parsed > 0L ? parsed : -1L; - } catch (NumberFormatException ex) { - return -1L; - } - } - private static long uniqueTenantId(List scopes) { List tenantIds = Objects.requireNonNull(scopes, "scopes must not be null").stream() - .map(scope -> parsePositiveLong(scope.playerContext().getTenantId())) + .map(ScopedRealm::localTenantId) .distinct() .toList(); if (tenantIds.size() != 1 || tenantIds.getFirst() <= 0L) { @@ -892,24 +886,19 @@ public record RealmsSnapshot( justification = "Generated protobuf execution contexts are immutable value messages.") public record ScopedRealm( String realmSlug, + long localTenantId, boolean publicProductionRealm, String connectScopeId, Instant expiresAt, PlayerExecutionContext playerContext, String joinRequestId) { - public ScopedRealm( - String realmSlug, - boolean publicProductionRealm, - String connectScopeId, - Instant expiresAt, - PlayerExecutionContext playerContext) { - this(realmSlug, publicProductionRealm, connectScopeId, expiresAt, playerContext, ""); - } - public ScopedRealm { if (realmSlug == null || realmSlug.isBlank()) { throw new IllegalArgumentException("realmSlug must not be blank"); } + if (localTenantId <= 0L) { + throw new IllegalArgumentException("localTenantId must be positive"); + } if (connectScopeId == null || connectScopeId.isBlank()) { throw new IllegalArgumentException("connectScopeId must not be blank"); } @@ -1044,6 +1033,7 @@ private record MemoryValue(String value, long expiresAtMillis) {} private record StoredScopedRealm( String realmSlug, + long localTenantId, boolean publicProductionRealm, String connectScopeId, long expiresAtEpochMs, @@ -1059,6 +1049,7 @@ private record StoredScopedRealm( private StoredScopedRealm withJoinRequestId(String requestId) { return new StoredScopedRealm( realmSlug, + localTenantId, publicProductionRealm, connectScopeId, expiresAtEpochMs, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java index cc8aabd897..4f9f5dcd03 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -82,10 +82,12 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( "production", + 22L, true, "account-connect-scope-17", now.plusSeconds(600), - playerContext(caller))), + playerContext(caller), + "")), now); firstInstance.replaceRealmSnapshot( caller, @@ -99,15 +101,21 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( "production", + 33L, true, "account-connect-scope-33", now.plusSeconds(600), - playerContext(caller, 33L))), + playerContext(caller, 33L), + "")), now); assertThat( replacementJoinScope(newStoreInstance(), caller, "2", 33L, "demo-world", Instant.now())) .satisfies( - selected -> assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("33")); + selected -> { + assertThat(selected.scope().playerContext().getTenantId()) + .isEqualTo(canonicalTenantId(33L)); + assertThat(selected.scope().localTenantId()).isEqualTo(33L); + }); List replacementInstances = java.util.stream.IntStream.range(0, 8).mapToObj(ignored -> newStoreInstance()).toList(); @@ -165,10 +173,12 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( "production", + 22L, true, "account-connect-scope-18", Instant.now().plusSeconds(600), - playerContext(caller))), + playerContext(caller), + "")), Instant.now()); String freshRequestId = firstInstance @@ -215,6 +225,8 @@ void readsLegacyLobbyJsonWithUnusedSelectorMapAcrossStoreInstances() throws Exce Map.of( "realmSlug", "production", + "localTenantId", + 22L, "publicProductionRealm", true, "connectScopeId", @@ -265,7 +277,9 @@ void readsLegacyLobbyJsonWithUnusedSelectorMapAcrossStoreInstances() throws Exce assertThat(selected.scope().playerContext().getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(selected.scope().playerContext().getSessionId()) .isEqualTo(Long.toString(SESSION_ID)); - assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); + assertThat(selected.scope().playerContext().getTenantId()) + .isEqualTo(canonicalTenantId(22L)); + assertThat(selected.scope().localTenantId()).isEqualTo(22L); assertThat(selected.requestId()).isEqualTo("join-request-already-bound"); }); assertThat(redisTemplate.opsForValue().get(REDIS_KEY)).doesNotContain("worldBySelector"); @@ -287,7 +301,7 @@ private static PlayerExecutionContext playerContext(SessionContext caller, long return PlayerExecutionContext.newBuilder() .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) - .setTenantId(Long.toString(tenantId)) + .setTenantId(canonicalTenantId(tenantId)) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") .setPlayableStateScope("SHARED") @@ -295,6 +309,14 @@ private static PlayerExecutionContext playerContext(SessionContext caller, long .build(); } + private static String canonicalTenantId(long localTenantId) { + return switch ((int) localTenantId) { + case 22 -> "22222222-2222-4222-8222-222222222222"; + case 33 -> "33333333-3333-4333-8333-333333333333"; + default -> throw new IllegalArgumentException("No test association for local tenant"); + }; + } + private static DirectTextConnectScopeSessionStore.JoinScope replacementJoinScope( DirectTextConnectScopeSessionStore store, SessionContext caller, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 67953fc9b7..ea6fc94ac2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.argThat; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; @@ -66,6 +67,7 @@ import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; import net.firedevops.firemud.gamesession.testsupport.InMemorySessionContextTestConfiguration; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import net.firedevops.firemud.shared.v1.RoomInstanceRef; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -570,7 +572,7 @@ void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { verify(accountClient, atLeastOnce()) .getTenantMembershipForRuntime( argThat( - request -> + (PlayerExecutionContext request) -> CANONICAL_TENANT_UUID.toString().equals(request.getTenantId()) && "1".equals(request.getGameInstanceId()) && "41".equals(request.getSessionId()))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 22234fbbee..22e224c064 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -908,7 +908,7 @@ void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { Mockito.eq("preview"), Mockito.anyString())) .thenReturn( - validGrant(PLAYER_ACCOUNT_ID, "22", "demo", "preview").toBuilder() + validGrant(PLAYER_ACCOUNT_ID, CANONICAL_TENANT_UUID, "demo", "preview").toBuilder() .setGranted(false) .build()); @@ -1572,14 +1572,7 @@ void playRejectsModerationPolicyDeniedAdmission() { void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding() { SessionContext context = new SessionContext( - 1L, - 22L, - PLAYER_ACCOUNT_ID, - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1588,9 +1581,8 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( freshMembership( - net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active( - PLAYER_ACCOUNT_ID, 22L, "22"), + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(PLAYER_ACCOUNT_ID, 22L, "22"), false), invocation.getArgument(0))); @@ -3320,7 +3312,10 @@ void playUnlistedNonPublicRealmInPublicWorldMasksDeniedGrantLikeUnknownSelection Mockito.eq("demo"), Mockito.eq("invite-only"), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn( + validGrant(PLAYER_ACCOUNT_ID, CANONICAL_TENANT_UUID, "demo", "invite-only").toBuilder() + .setGranted(false) + .build()); PlayCommandHandlingResult denied = handler.handle( @@ -5553,16 +5548,18 @@ private PlayCommandHandler handlerWithClock( } private static GetTenantMembershipForRuntimeResponse missingMembershipAt(String evaluatedAt) { - return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - PLAYER_ACCOUNT_ID, 22L) + return freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( + PLAYER_ACCOUNT_ID, 22L)) .toBuilder() .setEvaluatedAt(evaluatedAt) .build(); } private static GetTenantMembershipForRuntimeResponse activeMembershipAt(String evaluatedAt) { - return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - PLAYER_ACCOUNT_ID, 22L, "1") + return freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( + PLAYER_ACCOUNT_ID, 22L, "1")) .toBuilder() .setEvaluatedAt(evaluatedAt) .build(); @@ -5854,7 +5851,11 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); WorldsCommandHandler worldsCommandHandler = - new WorldsCommandHandler(worldCatalog, accountClient, connectScopeSessionStore); + new WorldsCommandHandler( + worldCatalog, + accountClient, + connectScopeSessionStore, + retainedRuntimeTenantUuidResolver); assertThat(worldsCommandHandler.browseRealms(resolvedContext, "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); WorldsTextCommandDispatchHandler worldsDispatchHandler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index d9fb6499ec..7303426d61 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -325,7 +325,10 @@ void setUp() { connectScopeSessionStore); worldsHandler = new WorldsCommandHandler( - worldCatalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + worldCatalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + retainedRuntimeTenantUuidResolver); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index c581c2a75b..0f091f4224 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -450,7 +450,10 @@ void setUp() { .build()); WorldsCommandHandler worldsHandler = new WorldsCommandHandler( - worldCatalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + worldCatalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + retainedRuntimeTenantUuidResolver); LookResult lookResult = LookResult.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index bc6e1d8497..c2de434993 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -39,13 +40,20 @@ class WorldsCommandHandlerTest { UUID.fromString("00000000-0000-0000-0000-000000000001"); private static final UUID ADMISSION_NAMESPACE_ID = UUID.fromString("00000000-0000-0000-0000-000000000002"); + private static final UUID TENANT_22_UUID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_23_UUID = + UUID.fromString("23232323-2323-4232-8232-232323232323"); + private static final UUID TENANT_33_UUID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); private final GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); private final WorldsCommandHandler handler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); @BeforeEach void setUp() { @@ -273,7 +281,8 @@ void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); localHandler.browseView("7", Optional.of(authenticatedSession())); worlds.set(List.of(worldB, worldA)); @@ -308,7 +317,8 @@ void ambiguousWorldSlugRejectsBareSelectionWhileBoundOrdinalsKeepTenantTargets() new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldA, worldB)), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); WorldsViewOutput worldSnapshot = localHandler.browseView("7", Optional.of(authenticatedSession())); @@ -335,32 +345,32 @@ void ambiguousWorldSlugRejectsBareSelectionWhileBoundOrdinalsKeepTenantTargets() .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); Mockito.verify(accountClient) .issueDirectTextConnectScope( - Mockito.argThat(context -> context.getTenantId().equals("22")), + Mockito.argThat(context -> context.getTenantId().equals(TENANT_22_UUID.toString())), Mockito.argThat( target -> - target.tenantId().equals("22") + target.tenantId().equals(TENANT_22_UUID.toString()) && target.worldSlug().equals("demo") && target.realmSlug().equals("production") && target.gameInstanceId().equals("1"))); Mockito.verify(accountClient) .issueDirectTextConnectScope( - Mockito.argThat(context -> context.getTenantId().equals("33")), + Mockito.argThat(context -> context.getTenantId().equals(TENANT_33_UUID.toString())), Mockito.argThat( target -> - target.tenantId().equals("33") + target.tenantId().equals(TENANT_33_UUID.toString()) && target.worldSlug().equals("DEMO") && target.realmSlug().equals("production") && target.gameInstanceId().equals("2"))); Mockito.verify(accountClient) .joinPublicProductionMembership( - Mockito.argThat(context -> context.getTenantId().equals("22")), - Mockito.eq("scope-22"), + Mockito.argThat(context -> context.getTenantId().equals(TENANT_22_UUID.toString())), + Mockito.eq("scope-" + TENANT_22_UUID), Mockito.anyString(), Mockito.any(Instant.class)); Mockito.verify(accountClient) .joinPublicProductionMembership( - Mockito.argThat(context -> context.getTenantId().equals("33")), - Mockito.eq("scope-33"), + Mockito.argThat(context -> context.getTenantId().equals(TENANT_33_UUID.toString())), + Mockito.eq("scope-" + TENANT_33_UUID), Mockito.anyString(), Mockito.any(Instant.class)); } @@ -378,7 +388,8 @@ void joinRejectsUnboundOrdinalBeforeCallingAccount() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -410,7 +421,8 @@ void joinForwardsTheRetainedAccountScopeExpiry() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -425,6 +437,56 @@ void joinForwardsTheRetainedAccountScopeExpiry() { Mockito.eq(scopeExpiresAt)); } + @Test + void unresolvedOrNilTenantAssociationDeniesRealmScopeIssuance() { + for (Optional association : + List.of(Optional.empty(), Optional.of(new UUID(0L, 0L)))) { + AccountClient accountClient = Mockito.mock(AccountClient.class); + RetainedRuntimeTenantUuidResolver resolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); + Mockito.when(resolver.resolveCanonicalTenantId(22L)).thenReturn(association); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(publicProductionProperties()), + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + resolver); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + } + } + + @Test + void changedTenantAssociationDeniesJoinBeforeAccountMembershipCall() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + RetainedRuntimeTenantUuidResolver resolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); + Mockito.when(resolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(TENANT_22_UUID), Optional.of(UUID.randomUUID())); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(publicProductionProperties()), + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + resolver); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verify(accountClient, Mockito.never()) + .joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any()); + } + @Test void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { GameplayWorldCatalog.RealmView realmA = @@ -474,7 +536,8 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); localHandler.browseView("7", Optional.of(authenticatedSession())); worlds.set(List.of(worldB, worldA)); @@ -488,7 +551,8 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { success -> assertThat(success.output().worldSlug()).isEqualTo("a")); Mockito.verify(accountClient) .issueDirectTextConnectScope( - Mockito.argThat(context -> context.getTenantId().equals("22")), Mockito.any()); + Mockito.argThat(context -> context.getTenantId().equals(TENANT_22_UUID.toString())), + Mockito.any()); } @Test @@ -541,7 +605,10 @@ void numericRealmSnapshotIgnoresPrivateReorderingAndRejectsPublicRoutingChanges( DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = new WorldsCommandHandler( - GameplayWorldCatalog.forWorldSupplier(worlds::get), accountClient, scopeStore); + GameplayWorldCatalog.forWorldSupplier(worlds::get), + accountClient, + scopeStore, + tenantUuidResolver()); assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) .isInstanceOfSatisfying( @@ -610,7 +677,8 @@ void browseRealmsToleratesNullRealmEnums() { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); RealmBrowseViewOutput response = localHandler.browseRealms("demo").orElseThrow(); @@ -770,7 +838,8 @@ void browseCharactersMapsMalformedRealmDiscoveryPointerToAdmissionPointerUnavail new WorldsCommandHandler( catalog, Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); @@ -968,7 +1037,7 @@ void browseCharactersRedactsPrivateOnlyWorldWithoutPublicProductionRealm() { DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = - new WorldsCommandHandler(catalog, accountClient, scopeStore); + new WorldsCommandHandler(catalog, accountClient, scopeStore, tenantUuidResolver()); assertThat(localHandler.browseCharacters(session, "preview", "unknown")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); @@ -1028,7 +1097,8 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); @@ -1109,7 +1179,8 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(incomplete)))), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) .isEqualTo( @@ -1215,7 +1286,7 @@ void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { Mockito.anyString())) .thenReturn(grant("demo", "preview", true)); WorldsCommandHandler localHandler = - new WorldsCommandHandler(catalog, accountClient, scopeStore); + new WorldsCommandHandler(catalog, accountClient, scopeStore, tenantUuidResolver()); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); @@ -1264,7 +1335,8 @@ void staleOrExpiredPrivateSnapshotCannotBindCurrentSameSlugTarget() { Mockito.anyString())) .thenReturn(grant("demo", "preview", true)); WorldsCommandHandler localHandler = - new WorldsCommandHandler(changingCatalog, accountClient, scopeStore); + new WorldsCommandHandler( + changingCatalog, accountClient, scopeStore, tenantUuidResolver()); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "preview")) .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.InvalidRealm("demo")); @@ -1373,7 +1445,10 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), accountClient, scopeStore); + TestGameplayWorldCatalogs.fromProperties(properties), + accountClient, + scopeStore, + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "public")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -1471,7 +1546,10 @@ void omittedCharactersInPrivateOnlyWorldRemainIndistinguishableFromUnknown() { DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), accountClient, scopeStore); + TestGameplayWorldCatalogs.fromProperties(properties), + accountClient, + scopeStore, + tenantUuidResolver()); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); @@ -1497,7 +1575,8 @@ void mixedRealmDiscoveryAndOmittedCharacterSelectionKeepOnlyPublicProductionTarg new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(publicWorldWithPrivateRealm()), accountClient, - scopeStore); + scopeStore, + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOfSatisfying( @@ -1612,7 +1691,8 @@ void authenticatedBrowseKeepsPublicScopeAndOrdinalWhileOmittingPrivateMetadata() new GameplayWorldCatalog.WorldView( "demo", "Demo", List.of(realm, privateRealm)))), accountClient, - scopeStore); + scopeStore, + tenantUuidResolver()); WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "demo"); @@ -1680,7 +1760,8 @@ void authenticatedBrowseCarriesGeneratedRequestIdIntoPublicScopeContext() { GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "demo"); @@ -1718,7 +1799,8 @@ void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySucces GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("REALM_UNAVAILABLE")); @@ -1783,7 +1865,10 @@ void joinRejectsRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); localHandler.browseView("7", Optional.of(authenticatedSession())); assertThat(localHandler.browseRealms(authenticatedSession(), "1")) @@ -1846,7 +1931,8 @@ void joinRejectsRetainedScopeWhenTenantPublicRealmBecomesAmbiguous() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "a")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -1915,7 +2001,10 @@ void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCar GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -1968,7 +2057,8 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -2011,7 +2101,17 @@ private WorldsCommandHandler authenticatedHandler( return new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(properties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); + } + + private static RetainedRuntimeTenantUuidResolver tenantUuidResolver() { + RetainedRuntimeTenantUuidResolver resolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); + Mockito.when(resolver.resolveCanonicalTenantId(22L)).thenReturn(Optional.of(TENANT_22_UUID)); + Mockito.when(resolver.resolveCanonicalTenantId(23L)).thenReturn(Optional.of(TENANT_23_UUID)); + Mockito.when(resolver.resolveCanonicalTenantId(33L)).thenReturn(Optional.of(TENANT_33_UUID)); + return resolver; } private void stubPublicConnectScope(AccountClient accountClient, String scopeId) { @@ -2311,7 +2411,8 @@ void publicBrowseDoesNotExposePrivateWorldOrRealmMetadata() { new WorldsCommandHandler( catalog, Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseView().worlds()) .extracting("slug") @@ -2346,7 +2447,8 @@ void charsPrivateOnlyWorldFailsBeforeEntityRead() { new WorldsCommandHandler( catalog, Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( @@ -2403,7 +2505,8 @@ void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { new WorldsCommandHandler( catalog, Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"); @@ -2449,7 +2552,10 @@ void charsDoesNotResolveHiddenRealmByDirectSlug() { AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()); assertThat(localHandler.browseCharacters(authenticatedSession(), "mixed-world", "secret")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidRealm("mixed-world")); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index eb1e76554b..35db207655 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -38,6 +39,8 @@ class WorldsTextCommandDispatchHandlerTest { private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final String ACCOUNT_A_UUID = "d0c68a37-5126-42d2-9506-8df13e97699e"; private static final String ACCOUNT_B_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private static final String TENANT_22_UUID = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_33_UUID = "33333333-3333-4333-8333-333333333333"; private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); @@ -50,7 +53,8 @@ class WorldsTextCommandDispatchHandlerTest { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); @Test @@ -121,7 +125,8 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); TextCommandDispatchRequest request = new TextCommandDispatchRequest( @@ -152,7 +157,8 @@ void worldsRejectsInvalidTransportSessionIdBeforeCatalogStoreOrEventDispatch( new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), Mockito.mock(AccountClient.class), - store), + store, + tenantUuidResolver()), scriptEventPublisher); TextCommandInterpretationResult result = @@ -175,7 +181,8 @@ void worldsDoesNotTranslateCatalogIllegalArgumentExceptionToInvalidArgument() { new WorldsCommandHandler( catalog, Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); assertThatThrownBy(() -> scopedHandler.handle(worldsRequest("7"))) @@ -201,7 +208,8 @@ void worldsDoesNotTranslateStoreIllegalArgumentExceptionToInvalidArgument() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of()), Mockito.mock(AccountClient.class), - store), + store, + tenantUuidResolver()), scriptEventPublisher); assertThatThrownBy(() -> scopedHandler.handle(worldsRequest("7"))) @@ -241,7 +249,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { GameplayWorldCatalog.RealmView currentRealm = catalog.visibleRealms(sandbox).getFirst(); DirectTextConnectScopeTarget expectedTarget = new DirectTextConnectScopeTarget( - Long.toString(currentRealm.tenantId()), + TENANT_22_UUID, sandbox.slug(), currentRealm.slug(), currentRealm.realmId().toString(), @@ -253,7 +261,10 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -334,7 +345,8 @@ void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -382,7 +394,8 @@ void closesPublicCharsBrowseBeforeAuthorityOrRosterReads() { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); TextCommandInterpretationResult result = scopedHandler.handle( @@ -415,7 +428,8 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -457,7 +471,8 @@ void routesExplicitPublicCharsBrowseToUnavailableBeforeAuthorityOrRosterReads() new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -522,7 +537,8 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { namespaceId))))); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( - new WorldsCommandHandler(catalog, accountClient, scopeStore), scriptEventPublisher); + new WorldsCommandHandler(catalog, accountClient, scopeStore, tenantUuidResolver()), + scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() @@ -604,6 +620,8 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .issueDirectTextConnectScope(callerCaptor.capture(), targetCaptor.capture()); assertThat(callerCaptor.getValue().getAccountId()).isEqualTo(ACCOUNT_ID); assertThat(callerCaptor.getValue().getSessionId()).isEqualTo("7"); + assertThat(callerCaptor.getValue().getTenantId()).isEqualTo(TENANT_22_UUID); + assertThat(targetCaptor.getValue().tenantId()).isEqualTo(TENANT_22_UUID); assertThat(targetCaptor.getValue().realmId()).isEqualTo(realmId.toString()); assertThat(targetCaptor.getValue().catalogRevision()).isEqualTo(7L); assertThat(targetCaptor.getValue().pointerVersion()).isEqualTo(4L); @@ -672,7 +690,10 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( @@ -756,7 +777,8 @@ void joinMissingSelectorRendersLocalizedErrorWithoutCallingAccount() { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); TextCommand command = new TextCommand(TextCommandType.JOIN, List.of(), "JOIN"); TextCommandInterpretationResult result = @@ -943,7 +965,10 @@ private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); SessionContext context = new SessionContext(7L, 22L, ACCOUNT_A_UUID, "emberline@example.com", 0L, null, 0L, "jwt"); @@ -1012,7 +1037,8 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + DirectTextConnectScopeSessionStore.inMemoryForTest(), + tenantUuidResolver()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -1057,4 +1083,14 @@ void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); } + + private static RetainedRuntimeTenantUuidResolver tenantUuidResolver() { + RetainedRuntimeTenantUuidResolver resolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); + when(resolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(TENANT_22_UUID))); + when(resolver.resolveCanonicalTenantId(33L)) + .thenReturn(Optional.of(UUID.fromString(TENANT_33_UUID))); + return resolver; + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 774d520826..a07819f849 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -325,7 +325,7 @@ void readsUuidLobbySnapshotAcrossProductionStoreInstances() { assertThat(selected.scope().connectScopeId()).isEqualTo("uuid-connect-scope"); assertThat(selected.scope().playerContext().getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); - assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); + assertThat(selected.scope().playerContext().getTenantId()).isEqualTo(canonicalTenantId(22L)); assertThat( firstInstance .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) @@ -371,13 +371,17 @@ void sameWorldSlugInDifferentTenantsKeepsOrdinalScopesIsolated() { .hasValueSatisfying( selected -> { assertThat(selected.scope().connectScopeId()).isEqualTo("tenant-22-scope"); - assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); + assertThat(selected.scope().playerContext().getTenantId()) + .isEqualTo(canonicalTenantId(22L)); + assertThat(selected.scope().localTenantId()).isEqualTo(22L); }); assertThat(store.publicProductionScopeForJoin(caller, "2", 33L, "demo", now)) .hasValueSatisfying( selected -> { assertThat(selected.scope().connectScopeId()).isEqualTo("tenant-33-scope"); - assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("33"); + assertThat(selected.scope().playerContext().getTenantId()) + .isEqualTo(canonicalTenantId(33L)); + assertThat(selected.scope().localTenantId()).isEqualTo(33L); }); assertThat(store.publicProductionScopeForJoin(caller, "2", 22L, "demo", now)).isEmpty(); assertThat(store.publicProductionScope(caller, "demo", now)).isEmpty(); @@ -583,6 +587,39 @@ void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { .isInstanceOf(DirectTextConnectScopeSessionStore.ConflictingIdentityException.class); } + @Test + void rejectsNumericTenantContextAndMismatchedLocalTenantMetadata() { + SessionContext caller = session(7L, ACCOUNT_UUID); + Instant now = Instant.now(); + DirectTextConnectScopeSessionStore.ScopedRealm valid = + scopedRealm(caller, 22L, "production", "scope-secret", now.plusSeconds(60)); + PlayerExecutionContext numericContext = + valid.playerContext().toBuilder().setTenantId("22").build(); + DirectTextConnectScopeSessionStore.ScopedRealm numericTenantScope = + new DirectTextConnectScopeSessionStore.ScopedRealm( + "production", 22L, true, "scope-numeric", now.plusSeconds(60), numericContext, ""); + assertThatThrownBy( + () -> + store.replaceWorldScopes( + caller, "demo", 22L, "demo", List.of(numericTenantScope), now)) + .isInstanceOf(DirectTextConnectScopeSessionStore.ConflictingIdentityException.class); + + DirectTextConnectScopeSessionStore.ScopedRealm mismatchedLocalTenantScope = + new DirectTextConnectScopeSessionStore.ScopedRealm( + "production", + 33L, + true, + "scope-wrong-local-key", + now.plusSeconds(60), + valid.playerContext(), + ""); + assertThatThrownBy( + () -> + store.replaceWorldScopes( + caller, "demo", 22L, "demo", List.of(mismatchedLocalTenantScope), now)) + .isInstanceOf(DirectTextConnectScopeSessionStore.ConflictingIdentityException.class); + } + private static SessionContext session(long sessionId, String accountId) { return new SessionContext(sessionId, 22L, accountId, 7001L, 9L, "jwt"); } @@ -622,13 +659,21 @@ private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( PlayerExecutionContext.newBuilder() .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) - .setTenantId(Long.toString(tenantId)) + .setTenantId(canonicalTenantId(tenantId)) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") .setPlayableStateScope("SHARED") .setGameInstanceId("9") .build(); return new DirectTextConnectScopeSessionStore.ScopedRealm( - realmSlug, true, scopeId, expiry, playerContext); + realmSlug, tenantId, true, scopeId, expiry, playerContext, ""); + } + + private static String canonicalTenantId(long localTenantId) { + return switch ((int) localTenantId) { + case 22 -> "22222222-2222-4222-8222-222222222222"; + case 33 -> "33333333-3333-4333-8333-333333333333"; + default -> throw new IllegalArgumentException("No test association for local tenant"); + }; } } From e10741ce7629d6c0117b2724d21feb6d456a6d56 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:42:55 +1300 Subject: [PATCH 18/22] test: make retained identity negative fixtures deterministic --- .github/workflows/ci.yml | 5 ++--- .../player-access-and-session.md | 4 ++++ ...ntAssociationRepositoryIntegrationTest.java | 5 ++++- ...ntAssociationRepositoryIntegrationTest.java | 18 ++++++++++++++---- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54f6b18266..511ee06ef5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -966,9 +966,8 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: game-design-owner-migration-proof-${{ github.sha }} - path: | - services/game-design-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest.xml - services/game-design-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest.xml + # Gradle may shorten long report filenames; strict verification binds suite/class names. + path: services/game-design-service/build/test-results/integrationTest/*.xml if-no-files-found: error - name: Run Game Session authored-world intake PostgreSQL component 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 4422da1a0b..907e3dc2e2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Exact source checkpoint `a80cd56f4488f97d9e8b7f4c70f2814503d54edf` [CI37197049562](https://github.com/benhook1013/FireMUD/actions/runs/37197049562) completed with aggregate failure. Game Design's configured isolated owner-schema case executed successfully. Its ten-case association suite executed with one failure: the malformed-signature fixture could leave an Ed25519 signature unchanged by replacing its existing suffix with the same bytes. The correction flips a decoded byte and proves inequality before retaining the rejection assertion; it changes no production signature or transaction guard. Game Session's retained-tenant suite raw XML proves seventeen executed, zero skipped, with one failure caused by two synthetic visible public-production pointers for tenant 1. The corrected fixture retains both visible targets and exact owner/association readback but explicitly marks only demo as public production; sandbox is not hidden to evade the constraint. Corrected-head PostgreSQL execution remains required for both repairs. Game Design's long report filenames also prevented the exact-path raw XML upload; the upload now retains the integration result directory's XML files, while strict suite/case verification remains unchanged. + +The same run's strict JUnit summaries prove Account JOIN 40, reconciliation 12, UUID storage migration 6, Social migration 8 and Logging migration 5 executed without skips, failures or errors; their jobs passed, but their raw XML was not uploaded. Game Design's baseline suite and later fresh-tenant/authored-world required proofs have no execution credit after the earlier failure. TCP's fourteen-case cross-service suite executed with thirteen failures, including `PLAY_IDENTITY_UNAVAILABLE` and a `game-session-service` DNS error; those logs do not prove a complete canonical identity or admission path. No aggregate-green, new complete producer, fresh-image/live proof or activation claim follows. After the parent-reviewed sandbox flag correction, the final local Game Design/Game Session checks, both boot JARs, formatting, analyzers, coverage and documentation gate passed in 1m11s (273 tasks: 30 executed, 243 up-to-date). Unit tasks reused unchanged results; Game Design's 52 integration cases all skipped without Docker, and Game Session executed 18 integration cases with 163 skipped. Corrected fixture PostgreSQL execution remains pending. Runtime activation and the Account ring mount remain denied. + The active [#2933](https://github.com/benhook1013/FireMUD/pull/2933) boundary retains Account password-reset and issuer source authority, exact retained-tenant UUID handoff, Game Logic UUID preservation and authenticated current/historical source transport proof. Its coherent Redis foundation/derived projection has moved to the existing [#2938](https://github.com/benhook1013/FireMUD/pull/2938) Account source child; the cumulative child tree is preserved exactly through normal history. That earlier regrouping reduced the parent scope from100 to77paths without dropping source implementation or proof; current reconciliation scope and exact-head proof are recorded on the owning PR. The reconciled REALMS/JOIN consumer candidate resolves only the exact namespace-qualified Game Session catalog-key association, sends its canonical tenant UUID unchanged in Account context and target, and stores the private catalog key separately. JOIN compares fresh association readback to the stored UUID before forwarding; absent, nil or changed evidence denies. Local mocked tests are component proof only. The Account direct-text scope/JOIN producer still parses private numeric caller/tenant fields and its runtime catalog reads do not yet prove canonical cross-owner tenant association. Canonical Account caller resolution, Account-owned tenant mapping, exact authenticated catalog evidence, durable scope/JOIN binding and composed positive/negative execution remain required before end-to-end availability. Do not forward a Game Session private key as an Account key, infer equality, or treat the consumer fixture as activation proof. Membership, credential/context/catalog/admission and ring gates remain unchanged. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 2a2e67693d..f0b3cd2df5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -304,8 +304,11 @@ void applyRequiresOwnerTransactionAndReadRequiresExactCommittedScope() throws Ex assertThatThrownBy(() -> fixture.apply(signed, "another-namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("different namespace"); + byte[] alteredSignatureBytes = Base64.getDecoder().decode(signed.ed25519Signature()); + alteredSignatureBytes[0] ^= 0x01; Signed malformedSignature = - new Signed(signed.manifest(), signed.ed25519Signature().substring(0, 84) + "AA=="); + new Signed(signed.manifest(), Base64.getEncoder().encodeToString(alteredSignatureBytes)); + assertThat(malformedSignature.ed25519Signature()).isNotEqualTo(signed.ed25519Signature()); assertThatThrownBy(() -> fixture.apply(malformedSignature, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("signature"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index 33d854f663..516a470687 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -160,6 +160,13 @@ void syntheticDemoFixtureDoesNotInventUnknownOrContradictoryTenantMappings() { void syntheticDefaultPointerTargetsRemainValidAcrossRepeatedFixtureBaselines() { Fixture fixture = fixture(); fixture.seedDefaultDemoAndSandboxPointers(); + var sandboxPointer = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT visible, public_production_realm FROM gameplay_admission_pointer WHERE id = ?", + 2L)); + assertThat(sandboxPointer.get("visible", Boolean.class)).isTrue(); + assertThat(sandboxPointer.get("public_production_realm", Boolean.class)).isFalse(); GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( fixture.jdbc, 1L, 1L, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, 501L); GameInstanceTestFixtures.ensureDeclaredRunningGameInstance( @@ -1014,7 +1021,8 @@ void seedDefaultDemoAndSandboxPointers() { "Demo", "Production", "a6eea203-4080-4db9-95e3-9ec838aff44a", - sharedNamespace); + sharedNamespace, + true); seedDefaultPointer( 2L, 2L, @@ -1023,7 +1031,8 @@ void seedDefaultDemoAndSandboxPointers() { "Sandbox", "Production", "bb8a798d-6706-472a-986b-7eb998748ec2", - sharedNamespace); + sharedNamespace, + false); } private void seedDefaultPointer( @@ -1034,7 +1043,8 @@ private void seedDefaultPointer( String worldName, String realmName, String realmId, - UUID sharedNamespace) { + UUID sharedNamespace, + boolean publicProductionRealm) { dsl.execute( "INSERT INTO gameplay_admission_pointer (" + "id, world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " @@ -1056,7 +1066,7 @@ private void seedDefaultPointer( "OPEN", "test/default-pointer-bootstrap", "synthetic retained-snapshot fixture", - true, + publicProductionRealm, UUID.fromString(realmId), sharedNamespace); } From 85e1b104c3087b72f73e5bd8018a5ddf79e7fbbb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 01:30:45 +1300 Subject: [PATCH 19/22] Select every required Game Design owner PostgreSQL proof suite --- .github/workflows/ci.yml | 12 +++++++----- .../player-access-and-session.md | 4 ++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 511ee06ef5..1d4eb1f392 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -941,24 +941,26 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false - - name: Run Game Design retained Game Session association PostgreSQL component proof + - name: Run complete Game Design owner component PostgreSQL proof if: ${{ matrix.module == 'game-design-service' }} run: | ./gradlew :game-design-service:integrationTest \ --tests integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ - --tests integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ + --tests net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ - --require-suite integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#appliesAuditedAssociationForFreshAndRetainedGameSources()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#versionLockRepositoryUsesConfiguredIsolatedOwnerSchema()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnOneImmutableReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#ownerRollbackLeavesNoClaimAndLostAcknowledgementRetryReadsExactReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges()' \ game-design-service - name: Retain Game Design owner migration raw PostgreSQL evidence 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 907e3dc2e2..91cf1f83f0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,9 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Exact source checkpoint `a80cd56f4488f97d9e8b7f4c70f2814503d54edf` [CI37197049562](https://github.com/benhook1013/FireMUD/actions/runs/37197049562) completed with aggregate failure. Game Design's configured isolated owner-schema case executed successfully. Its ten-case association suite executed with one failure: the malformed-signature fixture could leave an Ed25519 signature unchanged by replacing its existing suffix with the same bytes. The correction flips a decoded byte and proves inequality before retaining the rejection assertion; it changes no production signature or transaction guard. Game Session's retained-tenant suite raw XML proves seventeen executed, zero skipped, with one failure caused by two synthetic visible public-production pointers for tenant 1. The corrected fixture retains both visible targets and exact owner/association readback but explicitly marks only demo as public production; sandbox is not hidden to evade the constraint. Corrected-head PostgreSQL execution remains required for both repairs. Game Design's long report filenames also prevented the exact-path raw XML upload; the upload now retains the integration result directory's XML files, while strict suite/case verification remains unchanged. +Exact source checkpoint `e10741ce7629d6c0117b2724d21feb6d456a6d56` [CI37199764787](https://github.com/benhook1013/FireMUD/actions/runs/37199764787) completed with aggregate failure. Its raw XML proves all ten Game Design association and seventeen Game Session retained-association PostgreSQL cases executed with zero skips, failures or errors, including the configured isolated owner-schema case, signature-tampering guard and repeated visible-but-private sandbox fixture. This closes those preceding fixture execution gaps. Four retained Game Session snapshot cases also passed the strict job-log verifier, without matching raw XML; its later broad task was canceled and receives no completion credit. Game Design's Entity-baseline test used an incorrect fully qualified selector, and the targeted invocation omitted the required fresh-tenant and authored-world suites. The workflow now selects all four actual owner suites before retaining raw XML and running the unchanged strict suite/case gates. Corrected-head execution of those previously missing suites remains required; successful association execution does not substitute for it. -The same run's strict JUnit summaries prove Account JOIN 40, reconciliation 12, UUID storage migration 6, Social migration 8 and Logging migration 5 executed without skips, failures or errors; their jobs passed, but their raw XML was not uploaded. Game Design's baseline suite and later fresh-tenant/authored-world required proofs have no execution credit after the earlier failure. TCP's fourteen-case cross-service suite executed with thirteen failures, including `PLAY_IDENTITY_UNAVAILABLE` and a `game-session-service` DNS error; those logs do not prove a complete canonical identity or admission path. No aggregate-green, new complete producer, fresh-image/live proof or activation claim follows. After the parent-reviewed sandbox flag correction, the final local Game Design/Game Session checks, both boot JARs, formatting, analyzers, coverage and documentation gate passed in 1m11s (273 tasks: 30 executed, 243 up-to-date). Unit tasks reused unchanged results; Game Design's 52 integration cases all skipped without Docker, and Game Session executed 18 integration cases with 163 skipped. Corrected fixture PostgreSQL execution remains pending. Runtime activation and the Account ring mount remain denied. +The same run's strict JUnit summaries prove Account JOIN 40, reconciliation 12, UUID storage migration 6, Social migration 8 and Logging migration 5 executed without skips, failures or errors; their jobs passed, but corresponding raw XML was not uploaded. Python lint exposed an unbound callback loop variable; ten tooling tests lacked the locked WebSocket client dependency. Both findings are routed to their #2853 owner in the controller. TCP's seventeen-case cross-service suite had thirteen expected-PLAY failures, including `PLAY_IDENTITY_UNAVAILABLE`; this does not prove an enabled canonical identity/admission path or that DNS alone caused the failures. No aggregate-green, complete producer, fresh-image/live proof or activation claim follows. The preceding local Game Design/Game Session full checks, boot JARs, formatting, analyzers, coverage and documentation gate passed in 1m11s (273 tasks: 30 executed, 243 up-to-date); unchanged unit results were reused, all 52 Game Design integration cases skipped without Docker, and Game Session executed 18 with 163 skipped. Runtime activation and the Account ring mount remain denied. The active [#2933](https://github.com/benhook1013/FireMUD/pull/2933) boundary retains Account password-reset and issuer source authority, exact retained-tenant UUID handoff, Game Logic UUID preservation and authenticated current/historical source transport proof. Its coherent Redis foundation/derived projection has moved to the existing [#2938](https://github.com/benhook1013/FireMUD/pull/2938) Account source child; the cumulative child tree is preserved exactly through normal history. That earlier regrouping reduced the parent scope from100 to77paths without dropping source implementation or proof; current reconciliation scope and exact-head proof are recorded on the owning PR. From f982fd671d0187b38e24a53f3dfc4b06e9ebf285 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:24:00 +1300 Subject: [PATCH 20/22] Allow Validation for stacked pull requests --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d4eb1f392..c1764ea1d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: From 1e0a304077c7b8eec5836e995dabd3fbe974a9f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:35:19 +1300 Subject: [PATCH 21/22] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c1764ea1d3..13ecb152e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1429,7 +1429,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { From 7d01b8b4e47b9de1f3cb60f86571223677abc438 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:48:05 +1300 Subject: [PATCH 22/22] Carry forward locked Python contract-test fixes --- .github/workflows/ci.yml | 4 + .../test_hosted_websocket_playable_smoke.py | 9 +- .../workflow_version_authority_contract.py | 101 ++++++++++++++++++ 3 files changed, 110 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 13ecb152e0..115e23b2a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -320,6 +320,10 @@ jobs: with: requirements: ${{ (needs.changes.outputs.lightweight_only == 'true' && needs.changes.outputs.design_docs_changed == 'true' && needs.changes.outputs.validation_python_changed != 'true') && 'yaml' || 'ci' }} + - name: 📦 Install bounded wire test dependencies + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + run: python3 -m pip install --disable-pip-version-check --require-hashes -r config/python/smoke-requirements.txt + - name: 📦 Install cloc if: ${{ needs.changes.outputs.lightweight_only != 'true' }} env: diff --git a/dev-tools/tests/test_hosted_websocket_playable_smoke.py b/dev-tools/tests/test_hosted_websocket_playable_smoke.py index 869420d960..10e0107790 100644 --- a/dev-tools/tests/test_hosted_websocket_playable_smoke.py +++ b/dev-tools/tests/test_hosted_websocket_playable_smoke.py @@ -1050,13 +1050,14 @@ def test_connect_token_cookie_requires_full_protection_before_wss(self): for attributes, metadata in invalid_responses: http = FakeHttp(cookie_attributes=attributes, connect_token_metadata=metadata) socket_attempts = [] - with self.subTest(attributes=attributes, metadata=metadata), self.assertRaises( - MODULE.HostedWebSocketPlayableSmokeError + with ( + self.subTest(attributes=attributes, metadata=metadata), + self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError), ): MODULE.run_smoke( self.config(), http_request=http, - websocket_factory=lambda *args: socket_attempts.append(args), + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), ) self.assertEqual(socket_attempts, []) @@ -1066,7 +1067,7 @@ def test_connect_token_cookie_accepts_full_protection_and_token_ttl(self): MODULE.run_smoke( self.config(), http_request=http, - websocket_factory=lambda *args: (socket_attempts.append(args) or FakeWebSocket()), + websocket_factory=lambda *args: socket_attempts.append(args) or FakeWebSocket(), ) self.assertEqual(len(socket_attempts), 1) diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index dd34d2b6ae..45d7032609 100644 --- a/dev-tools/tests/workflow_version_authority_contract.py +++ b/dev-tools/tests/workflow_version_authority_contract.py @@ -139,6 +139,8 @@ def read_lock(path): for name, (entries, includes) in locks.items(): if includes: fail(f"{name} requirements must not include another profile") + if "websocket-client" not in locks["smoke"][0]: + fail("smoke requirements must pin the bounded WebSocket test dependency") for dependency in expected_direct_requirements["docs"]: if dependency not in locks["docs"][0]: fail(f"docs requirements must pin its direct dependency in the generated lock: {dependency}") @@ -591,6 +593,55 @@ def validate_workflow_python_steps(path, job_name, steps): fail(f"{path.name}:{job_name}: {need} helper lacks its pinned dependency profile") return setup_count + smoke_requirements_install = ( + "python3 -m pip install --disable-pip-version-check --require-hashes -r config/python/smoke-requirements.txt" + ) + full_validation_guard = "${{ needs.changes.outputs.lightweight_only != 'true' }}" + full_validation_commands = { + "python3 -m unittest discover -s dev-tools/validation -p 'test_*.py'", + "python3 -m unittest discover -s dev-tools/tests -p 'test_*.py'", + } + + def validate_dev_tool_smoke_dependencies(path, steps): + setup_indices = [ + index + for index, step in enumerate(steps) + if isinstance(step, dict) and step.get("uses") == "./.github/actions/setup-python" + ] + if len(setup_indices) != 1: + fail(f"{path.name}:dev-tool-contract-checks must set up Python exactly once") + setup_index = setup_indices[0] + install_indices = [ + index + for index, step in enumerate(steps) + if isinstance(step, dict) and "pip install" in str(step.get("run", "")) + ] + if len(install_indices) != 1: + fail(f"{path.name}:dev-tool-contract-checks must install the smoke lock exactly once") + install_index = install_indices[0] + install_step = steps[install_index] + if install_index != setup_index + 1: + fail(f"{path.name}:dev-tool-contract-checks smoke lock must install immediately after Python setup") + if str(install_step.get("run", "")).strip() != smoke_requirements_install: + fail(f"{path.name}:dev-tool-contract-checks must install the hash-locked smoke requirements") + if install_step.get("if") != full_validation_guard: + fail(f"{path.name}:dev-tool-contract-checks smoke lock install must be limited to full validation") + + full_discovery = [] + for index, step in enumerate(steps): + if not isinstance(step, dict): + continue + run_lines = {line.strip() for line in str(step.get("run", "")).splitlines()} + if full_validation_commands <= run_lines: + full_discovery.append((index, step)) + if len(full_discovery) != 1: + fail(f"{path.name}:dev-tool-contract-checks must retain full unittest discovery") + discovery_index, discovery_step = full_discovery[0] + if discovery_index <= install_index: + fail(f"{path.name}:dev-tool-contract-checks must install smoke requirements before full discovery") + if discovery_step.get("if") != full_validation_guard: + fail(f"{path.name}:dev-tool-contract-checks full unittest discovery must remain on full validation") + if python_needs("bash ./dev-tools/tests/dev-tools-readme-contract.sh") == "smoke": fail("documentation/data references must not imply the smoke dependency profile") if python_needs("bash ./services/game-session-service/websocket-login-look-smoke.sh") != "smoke": @@ -796,6 +847,19 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j ], "profile-sequencing: smoke helper lacks its pinned dependency profile", ) + expect_workflow_failure( + [workflow_checkout, {"run": smoke_requirements_install}], + "profile-sequencing: direct or helper Python consumer uses ambient runner Python", + ) + expect_workflow_failure( + [ + workflow_checkout, + {"uses": "./.github/actions/setup-python", "with": {"requirements": "ci"}}, + {"run": smoke_requirements_install}, + {"run": python_smoke_reference}, + ], + "profile-sequencing: smoke helper lacks its pinned dependency profile", + ) conditional_setup = { "uses": "./.github/actions/setup-python", @@ -844,6 +908,41 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j job_name="dev-tool-contract-checks", ) + valid_full_run = { + "if": full_validation_guard, + "run": "\n".join(sorted(full_validation_commands)), + } + valid_smoke_install = {"if": full_validation_guard, "run": smoke_requirements_install} + valid_smoke_dependency_steps = [workflow_checkout, conditional_setup, valid_smoke_install, valid_full_run] + validate_dev_tool_smoke_dependencies(ci_workflow_fixture, valid_smoke_dependency_steps) + + def expect_smoke_dependency_failure(steps, expected_message): + try: + validate_dev_tool_smoke_dependencies(ci_workflow_fixture, steps) + except SystemExit as error: + if expected_message not in str(error): + fail(f"smoke dependency fixture failed for an unexpected reason: {error}") + else: + fail(f"smoke dependency fixture unexpectedly passed: {expected_message}") + + expect_smoke_dependency_failure( + [ + workflow_checkout, + conditional_setup, + {**valid_smoke_install, "run": valid_smoke_install["run"].replace("--require-hashes ", "")}, + valid_full_run, + ], + "must install the hash-locked smoke requirements", + ) + expect_smoke_dependency_failure( + [workflow_checkout, conditional_setup, {**valid_smoke_install, "if": None}, valid_full_run], + "smoke lock install must be limited to full validation", + ) + expect_smoke_dependency_failure( + [workflow_checkout, conditional_setup, valid_smoke_install], + "must retain full unittest discovery", + ) + workflow_paths = sorted((*workflows.glob("*.yml"), *workflows.glob("*.yaml"))) expected_permissions = { @@ -935,6 +1034,8 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j continue steps = job.get("steps", []) python_count += validate_workflow_python_steps(path, job_name, steps) + if path.name == "ci.yml" and job_name == "dev-tool-contract-checks": + validate_dev_tool_smoke_dependencies(path, steps) checkout = gh_setup_seen = loader = False for step in steps: if not isinstance(step, dict):